Graphing and Exporting with LabTalk


Summary

There are many commands, objects and x-functions in LabTalk, that can be used to create and customize 2D or 3D graphs and export them either as image or video files.

What You Will Learn

This tutorial will show you how to use LabTalk script to:

  • Create 2D graph
  • Create 3D graph
  • Customize axes and data plots in a graph
  • Export a graph as image file
  • Export a combination of several graphs as a video

As written, the scripts are designed to be executed sequentially within each example.

Steps

Create Graphs

2D Graphs

  1. Run the script below to create a new workbook named Graph2D and import the Waterfall.dat file under <Origin EXE Folder>\Samples\Graphing\ using an import filter waterfall.oif. The ImpFile x-function is used in this case.
  2. // Create a newbook and name it Graph2D (both long and short name)
    newbook name:="Graph2D" option:=lsname;
    // Define the file name and filter name
    string fname$ = system.path.program$ + "Samples\Graphing\Waterfall.dat";
    string filtername$ = "waterfall.oif";  
    // Use the impfile x-function to import the specified file with the import filter
    impfile fname:=fname$ filtername:=filtername$ location:=data orng:=[Graph2D]1!;
  3. Create a line and symbol plot using 1st column as X and 2nd column as Y of the imported data in workbook Graph2D, using the plotxy x-function.
  4. // Generate a line and symbol XY plot with user defined R G B color
    plotxy iy:=[Graph2D]1!(1,2) plot:=202 color:=color(255,0,255);
    // Use string register to get the short name of the graph you just created
    %A = %H;
  5. Add another data plot to the graph you just created, but this time specify the layer to plot into.
  6. plotxy iy:=[Graph2D]1!(1,126) plot:=202 ogl:=[%A]1!;
  7. Create another graph using the built-in template doubleY.
  8. // Define a range for the source data worksheet
    range rr = [Graph2D]1!;
    // Plot a line+symbol graph into the first (active) layer of the Graph using built-in template '''doubleY''', with 1st column as X and 2nd column as Y
    plotxy iy:=%(rr)(1,2) plot:=202 ogl:=[<new template:=doubleY>];
    // Add a line plot into the 2nd layer of the graph, with 1st column as X, 126th column as Y
    plotxy iy:=%(rr)(1,126) plot:=200 ogl:=2!;
    //Retrieve the name of the new graph and store it in the string variable str1
    string str1$ = page.name$;

3D Graphs

  1. Use the following script to import the file XYZ Random Gaussian.dat under the path <Origin EXE>\Samples\Matrix Conversion and Gridding\.
  2. // Create a new workbook
    newbook;
    // Specify the filename
    string str2$ = "Samples\Matrix Conversion and Gridding\XYZ Random Gaussian.dat";
    // Include the file path
    string fname$ = system.path.program$ + str2$;
    // Import using the impASC X-Function
    impASC fname:=fname$;
    //Use a string register to get the workbook name
    %B = %H;
  3. Set the third column to be Z column using the wks.col object.
  4. // Set the type of the third column to be Z using the stored string register variable
    %B!wks.col3.type = 6;
  5. Use the plotxyz x-function to create a 3D colormap surface plot.
  6. // Make our data worksheet active
    win -a %B;
    // Create a 3D Colormap Surface plot from the selected worksheet data
    plotxyz iz:=3 plot:=103 ogl:=<new template:=glcmap>;
    //Get the graph window name to the string variable str3
    string str3$ = page.name$;

Note: You can also use the worksheet -p command to create both 2D and 3D graphs, provided you use the worksheet -s command to select desired input data range first.

Customize Graphs

A graph window is comprised of a visual page, with an associated Page object. Each graph page contains at least one visual layer, with an associated layer object. The graph layer contains a set of X Y axes with associated layer.x and layer.y objects, which are sub-objects of the layer object. With LabTalk access to these objects, you will be able to control page, layer and axes properties.

To customize the data plot, you can use the set command. You will also find the label command useful when you need to customize text objects on a graph.

In addition, there are several x-functions to manipulate a graph.

We will continue using the project file from the previous section:

  1. Run the following script to set the axis type of the first graph we created.
    //Activate the graph window
    win -a %A;
    //Change the Y axis type to be log10 and its from value to be 0.003
    layer.y.type = 2;
    layer.y.from = .003;
    //Change the Y axis title to be "Amplitude"
    label -yl Amplitude;
    //Show top X and right Y axes
    layer.x.showAxes = 3;
    layer.y.showAxes = 3;
    //Show major grid as dash for X axis
    layer.x.showGrids = 1;
    layer.x.grid.majorType = 2;
  2. Then use the set command to customize the second data plot.
  3. //Make sure the graph window we first created is active
    //If it's already active, you do not need to run the following line
    win -a %A;
    //Activate the second data plot.
    layer.plot = 2;
    //Set symbol shape to be Cross(X)
    set %C -k 7;
    //Set the plot line color to be blue
    set %C -cl 4;
    //Set the symbol edge color to be olive 
    set %C -cse 12;
  4. Now run this script to customize the double Y plot
  5. //declare range for first dataplot in layer 2 of the double Y plot
    range r2 = [%(str1$)]2!1;
    //set line to dash
    set r2 -d 1;
    //Activate the graph window of Double Y plot to view the change
    win -a %(str1$);
  6. Use the legendupdate x function to update the legend of the double Y plot.
  7. //Pre define the worksheet range of source data
    range rw=[Graph2D]1!;
    //Make sure the graph window we first created is active
    //If it's already active, you do not need to run the following line
    win -a %(str1$);
    //Update Legend with legendupdate x-function
    //Legend will be name + value of the first user defined parameter
    //@LD1 means the first user-defined parameter
    legendupdate mode:=7 custom:="%(rw.UserParam1$)-@LD1";
  8. Use the layer -3d r command to rotate the 3D graph.
  9. //Active the graph window for the 3D plot we just created
    win -a %(str3$);
    //Rotate around vertical direction by 90 degree.
    layer -3d r V 90;
    //You need to refresh to view the customized graph
    doc -uw;

Export Graphs

Export as Image

You can export one or more graphs to image file(s) by calling the expGraph x-function. To control export setting of images, you can use the tr1 or tr2 tree.

  • Use the following script to export all graph in current project as tip image to the user files folder (path stored in the %Y string register), and set width to be 600 pixel, DPI resolution to 100 and compression method to LZW. The exported file names will be defined as a combination of graph window long name and the system date by then:
  • doc -e P
    {
    expGraph type:=pdf filename:="<long name>-$(System.Date(),D11)" path:=%Y
         tr.Margin:=2 
         tr1.Unit:=2 
         tr1.Width:=600 
         tr2.TIF.DotsPerInch:=100
         tr2.TIF.Compression:=LZW;
    }

To simplify the script writing, you can open the expGraph dialog (File:Export Graphs), change setting in the dialog, and click the triangle button next to the Dialog Theme and choose Generate Script to generate labTalk script with the same setting.

Export as Video

You can use the vw object to export graphs as a video.

  • Run the following script to export a video showing the change of spectrum shape with increasing excitation wavelength. The data is from the Graph2D workbook.
  • //Define the compression method of MPEG4
    int codec = vw.FourCC('F','M','P','4'); 
    //Check whether this compression method is supported
    //If not supported, no compression will be used.
    if(vw.IsCodecInstalled(codec) == 0) 
    codec = 0; 
     
    //Define the file name of the video as ''<User Files Folder>\test.avi''
    //Use the string register %Z to store the file path and name
    %Z = %Ytest.avi;
    // Create video writer. (fileName, codec, framesPerSec, width, height)
    int err = vw.Create(%Z, codec, 8, 1024, 768);
    if( 0 == err )
    {
           //Define a range for source data worksheet
            win -a Graph2D;
            range rw1 = [Graph2D]1!;
           //Create the very first graph to start with
            plotxy iy:=%(rw1)2 plot:=200;
           //Customize the Y axis scale and increment
            layer.y.to = 3250;
            layer.y.inc = 500;
            //Update legend
            legendupdate mode:=7 custom:="%(rw1.UserParam1$)-@LD1";
            // Place legend
            legend.y = layer.y.to;
            legend.x = layer.x.to - legend.dx / 2;
            //Use the following loop to replace the plot data in the graph
            //Add each graph to be a frame in the video 
    	for(int a=3; a<=rw1.nCols; a++)
    	{
                   //Define the range of current displayed dataset
                   range ra = %(rw1)col($(a-1));
                   //Define the range of new dataset
                    range rb = %(rw1)col($(a));
                    //Clear the current data plot
                    layer -e ra;
                   //Add the new dataset to the graph
                    layer -i rb;
                   //Change the Y axis title
                    label -yl Amplitude;
                   //Refresh the graph
                  doc -uw;
    	 //Wait for graph window to redraw.
    	//This allows watching the animation while creating the video file.
    	sec -pw %h;
    	// Write each graph to video as 2 frames.
    	err = vw.WriteGraph(%h,2);
    	if( err )
                        break;
    	}
     
    	//Release the video writer.
    	vw.Release();
     
    	if( err )
    		type "WriteGraph error $(err)";
    }
    else
    	type "VideoWriter Create error $(err).";