FE 'tkGooie' Utilities

'PLOTtools' group

tkGnuplot 3Dsurface Or 2Dcontour _fromExprFxy

a GUI 'front-end' for 'gnuplot'

(FE = Freedom Environment)

A surface plot from
this FE 'tkGooie'
'front end' to 'gnuplot'
---
using a usr-specified
function f(x,y)
entered on the GUI

FE Home Page > FE Downloads Page >

FE 'tkGooies' Description Page >

FE 'tkGooies' 'PLOTtools' Page >

This
'tk Gnuplot 3D surface Or 2D contour
from Expression f(x,y)' code Page

INTRODUCTION to
Tcl-Tk code for Tk-GUI
'tkGnuplot3DsurfaceOr2Dcontour_ fromExprFxy'

In 2015 October, I provided a couple of Tk scripts that use 'gnuplot' to

and

On those pages, I pointed out that it may be 2016 or so before I get around to getting some auto-plot-scaling and auto-ticmarking code into releasable form --- in some pure-Tcl-Tk 'PlotQuik' X-Y plotting scripts that are on my 'to-do' list.

I need to make that autoscale and auto-ticmarking code more robust (and modular).

So, as a relatively quick-to-implement alternative, I decided to make some Tk GUI 'front-ends' for the popular, widely-available 'gnuplot' program.

I wanted to make some plot utilities for

  1. XY plots of 2 or 3 columns of data from a data file

  2. XY plots from math expressions of the form f(x)

  3. 3D surface plots from math expressions of the form f(x,y)

  4. bar charts from a data file

  5. one or two other 'gnuplot' front ends

The two Tk scripts for items 1 and 2 above are posted in the pages whose links are above.

On this page, I present the code of a Tk script for item 3 above.

The code is presented further below.


THE GOALS

I had some general goals for the Tcl-Tk 'front-end' script for this GUI.

Those goals were shaped by the capabilities of the 'gnuplot' program with regard to doing plots of functions of the form f(x,y), where the value of f(x,y) is thought of as values along a z-axis.

In addition to 3D surface plots, 'gnuplot' is capable of doing 2D contour line plots of 'iso-levels' of the function f(x,y).

And 'gnuplot' can do 2D 'heatmaps' by translating the z-heights into 'heat-colors' plotted in an x-y plane.

Furthermore, 'gnuplot' is capable of doing plots of various combinations of

  • 3D surface

  • 2D contour

  • 2D heatmap

After finding example scripts of these types of plots, I decided to implement five types of f(x,y) data plots:

  • 3D surface only

  • 2D contour only

  • 2D heatmap only

  • 3D surface and 2D contour

  • 2D contour and 2D heatmap

As I proceeded in the coding and testing of these several Tk GUI 'front-ends' to 'gnuplot', my knowledge of the capabilities of 'gnuplot' with regard to 2D and 3D plotting advanced, and some of my initial goals were augmented or altered.

Below are the main goals to which I gravitated for this Tk GUI.

  • Provide an entry field for a math expression of the type f(x,y).

  • To make it easy for a user to get started plotting, provide a listbox (on the left of the GUI), from which the user can select sample math expressions --- to put in the math expression entry field.

    The user can simply change coefficients and do a plot --- or more drastically change a selected math expression.

  • Provide 4 entry fields so that the user can tailor the plot title, and the x-axis and y-axis and z-axis titles, as desired.

    (By adjusting leading spaces in these titles, the user can have some control on the placement of those titles on the plot.)

  • Provide a row of buttons at the top of the GUI with labels such as 'Exit', 'Help', 'RePlot', and some color buttons to allow for setting some color options that are available with 'gnuplot'.

  • Provide 5 radiobuttons by which to specify which type of plot to render: 3D surface, 2D contour, 2D heatmap, 3Dsurface-2Dcontour, 2Dcontour-2Dheatmap.

  • Provide 6 entry fields so that the user can specify min and max values for the x and y and z axis scales.

    (Initialize each of these fields to an asterisk ... * ... which is to signal to 'gnuplot' to autoscale --- i.e. tells 'gnuplot' to automatically choose the min and max axis-extent values --- those mins and maxes which are indicated by an asterisk instead of a number.)

  • Provide radiobuttons for some of the output ('terminal type') options of 'gnuplot' --- GIF, PNG, JPEG, PS (Postscript color), PSbw (Postscript black-and-white), SVG (Scalable Vector Graphics), and WXT (a high-quality terminal type).

    In addition, provide a 'TestImg' button next to these radiobuttons, to take advantage of a 'gnuplot' ability to put out a 'test image' for any of the 'terminal types' --- showing the line-types and text orientation options and other options for the terminal type.

  • Provide 2 entry fields by which to specify the size of the image output (x-pixels, y-pixels).

  • Provide for specifying some 'surface plot options':

    • number of data samples to evaluate in x and y directions,

    • whether to make the surface plot a 'shaded' or a 'hatched' plot,

    • choose from about 7 different hatching options.

  • Provide for specifying '3D viewing options' --- what gnuplot calls 'polar' and 'azimuthal' angles.

  • Provide for specifying some 'contour line plot options':

    • number of contour 'levels' to depict,

    • number of data samples to evaluate in x and y directions, for contouring,

    • a width for the contour lines.

  • Provide for specifying 'heatmap (and potentially other) color palette options' :

    I chose to allow specifying 5 colors and 'spacing' for those colors in a color spectrum.

    In addition, provide a 'ShoPalette' button next to the 5 color-spectrum-setting widgets --- to take advantage of a 'gnuplot' ability to put out a 'spectrum image' from a set of colors and their 'relative' locations along the spectrum.

    (Those 'locations' can be from zero to one, minus-ten to plus-ten, zero to 99, whatever.)

  • Provide for specifying some 'key (legend) options' :

    Allow the user to specify the location of the key on the plot --- and the numeric format for the numbers next to the color/dashed lines in the legend.

    (The legend is usually used for contour line levels.)

  • Provide X,Y,Z entry fields, by which to specify an angle by which to orient the X and Y and Z tic-mark-labels on the axes.

    Default all to 0.

    (In some cases, '-45' can be handy for long labels on x-tic-marks.)


THE GUI LAYOUT

Like for some other Tk GUI scripts that I posted here at freedomenv.com, I made an initial 'text-sketch' for the GUI for this 'gnuplot' 'front-end' utility.



  CONVENTIONS for the GUI 'text-sketch' below:

   * SQUARE-BRACKETS indicate a comment not to be included on the GUI.
   * BRACES indicate a Tk 'button' widget.
   * UNDERSCORES indicate a Tk 'entry' widget.
   * A COLON indicates that the text before the colon is on a 'label' widget.
   * CAPITAL-O indicates a Tk 'radiobutton' widget.
   * CAPITAL-X indicates a Tk 'checkbutton' widget (if any).
   * Vertical bars (and horizontal hyphens) outline a 'listbox' widget.
   * Less-than and greater-than signs indicate the left and right ends of a horizontal 'scrollbar'.
   * Capital-V and Capital-A letters indicate the bottom and top ends of a vertical 'scrollbar'.


  Here is the sketch:


  FRAMEnames
  VVVVVVVVVV
              ------------------------------------------------------------------------------------------
              Gnuplot - 3D-SURFACE and/or 2D-CONTOUR plot of a math expression, f(x,y)
              [window title]
              ------------------------------------------------------------------------------------------

  .fRbuttons  {Exit} {Help} {RePlot} {Color of  {Color of    {Clear} {Autoscale}
                                      Lines}     background}   
    
               [.fRbottom FRAME contains the '.fRleft' and 'fRright' FRAMES]

               [ '.fRleft' FRAME   [ '.fRright FRAME'
                    is below ]         is below and to the right ]
  [FRAMES below
  are in .fRright
  -------------]

  .fRexpr      |---------------A Expression: sin(2.0*pi*x+0.5)*cos(1.0*pi*y+1.2)___________________________________
               |               |
  .fRtitle     |               | Plot title: __________Plot TITLE goes here________________________________________
               |               |
  .fRplottype  |               | O 3D-Surface  O 2D-Contour-lines  O 2D-HeatMap  O Surface-and-ContourLines O ContourLines-and-HeatMap
               |               |
  .fRxaxis     |    [ This     | XaxisMin: *_____  XaxisMax: *______ XticLabelsAngle: 0__  ___X-axis label goes here____
               |   listbox     |
  .fRyaxis     |    contains   | YaxisMin: *_____  YaxisMax: *______ YticLabelsAngle: 0__  ___Y-axis label goes here____
               | f(x,y) math   |
  .fRzaxis     | expressions ] | ZaxisMin: *_____  ZaxisMax: *______ ZticLabelsAngle: 0__  ___Z-axis label goes here____
               |               |
  .fRsurfopts  |               | SurfaceGridSamples .. Xdirection: 30__  Ydirection: 30__  X ShadeSurface? SurfaceHatchType(1-7): 3_
               |               |
  .fRsurfview  |               | 3D View angles .. Polar(1-180): 45_  Azimuthal(0-360): 45_   {OverheadView} {ObliqueView}
               |               |
  .fRcntropts  |               | ContourLevels: 10_   ContourGridSamples(x-and-y): 150_  ContourLineWidth: 1.5_
               |               |
  .fRheatopts  |               | HeatColors: {Low Color} {Low-Mid Color} {High-Mid Color} {High Color}
               |               |
  .fRkeyopts   |               | NumberFormatInKey: %.1f__  Examples: %8.2f  %.1f   KeyLocation: at 0,0 top left____________
               |               |
  .fRoutopts   |               | ImageOutType: O GIF O PNG O JPG O PSc OPSbw O SVG O WXT {TestImg}  Xpixels: 800__ Ypixels: 600__ 
               |               |
  .fRmsg       |<------------->V [ ..........  Messages go here  ......................................................]


From the GUI 'sketch' above, it is seen that the GUI is to consist of about

  • 14 button widgets
  • 26 label widgets
  • 26 entry widgets
  • 12 radiobutton widgets in 2 groups
  • 1 listbox widget with 2 scrollbars
  • 1 checkbutton widget
  • 0 scale widgets
  • 0 text widgets
  • 0 canvas widgets

Below is an image of the GUI that I ended up with for a 'first release'.


Poke this image to see the image
in a separate window or tab.

Note the initial message at the bottom of the GUI, indicating that the user can immediately get a plot by simply clicking on the 'RePlot' button.

After you do a plot, you typically see the names of a couple of files (the gnuplot script file and an output image file, if any) in the message line at the bottom of the GUI.

The 6 min,max entry fields are defaulted to an asterisk, which is used to tell 'gnuplot' to automatically determine those 6 limits.

After doing some experimenting with various axis limits, the user can quickly go back to 'autoscale' mode by clicking the 'Autoscale' button. An asterisk is put into the six min,max entry fields.

As I use this utility, I may find that I want to alter the GUI somewhat. If I make some significant changes, I intend to replace the script file here with the new file.

Anyone who wants to take the code on this page and alter the GUI to meet their needs is welcome to do it.

This Tk GUI script is meant to be an actual 'productivity' tool (not a toy) --- a free and open-source tool --- a tool that is open to enhancement and 'tweaking'.


DESCRIPTION OF THE CODE

Below is a link to the code that produced this GUI.

I follow my usual 'canonical' structure for Tk code, for this Tk script:



  0) Set general window & widget parms (win-name, win-position,
     win-color-scheme, fonts, widget-geometry-parms, win-size-control).

  1a) Define ALL frames and sub-frames.
  1b) Pack   ALL frames and sub-frames.

  2) Define & pack all widgets in the frames.

  3) Define keyboard or mouse/touchpad/touch-sensitive-screen
     action BINDINGS, if needed.

  4) Define PROCS, if needed.

  5) Additional GUI initialization (typically with one or more of
     the procs), if needed.


This Tk coding structure is discussed in more detail on the page A Canonical Structure for Tk Code --- and variations.

This makes it easy for me to find code sections --- while generating and testing Tk scripts, and when looking for code snippets to include in other Tk scripts (code re-use).


Experimenting with the GUI

As in all my scripts that use the 'pack' geometry manager (which is all of my 100-plus Tk scripts, so far), I provide the four main 'pack' parameters --- '-side', '-anchor', '-fill', and '-expand' --- on all the 'pack' commands for the frames and widgets.

I think I have found a good setting of the '-side', '-anchor', '-fill', and '-expand' parameters on the 'pack' commands for the various widgets of this GUI.

In particular ...

The math-expression, plot-title, and axis-titles entry widgets expand/contract appropriately when the window size is changed --- and button and label widgets stay fixed in size and relative-location as the window size is changed.

Furthermore, radiobuttons and entry fields for axis-limits, view angles, sampling numbers, line-width, color spectrum locations, pixel-sizes, etc. stay fixed in size.

If anyone wants to change the way the GUI configures itself as the main window size is changed, they can experiment with the '-side', '-anchor', '-fill', and '-expand' parameters on the 'pack' commands for the various widgets --- to get the widget behavior that they want.

---

Additional GUI experimentation:

You could change the fonts used for the various GUI widgets.

For example, you could change '-weight' from 'bold' to 'normal' --- or '-slant' from 'roman' to 'italic'.

Or change font families.

In fact, you may NEED to change the font families, because the families I used may not be available on your computer --- and the default font that the 'wish' interpreter chooses may not be very pleasing.

Furthermore, there are variables used to set geometry parameters of widgets --- parameters such as relief-type, border-widths, and padding.

Feel free to experiment with those parameters as well.

---

Note that the many (7) 'Color' buttons call on an RGB color-selector-GUI script to set the colors.

You can make that color-selector script by cutting-and-pasting the code from the page offering 'a non-obfuscated color selector GUI', on this site.


Some features of the code

There are plenty of comments in the code to describe what most of the code-sections are doing.

See the 'PROCS' section of the code to see the code in all the procs that are used in this Tk script.

Here is a list of the procs in this Tk script:

  • listboxSelectionTOexprField
  • clear_expr
  • set_autoscale
  • replot
  • plot_surface
  • plot_contour
  • plot_heatmap
  • plot_surface-contour
  • plot_contour-heatmap
  • edit_inputs
  • display_test_img
  • show_palette_gradient
  • getset_color
  • update_color_button
  • popup_msgVarWithScroll

The main plotting code is in the five 'plot_*' procs, which are called by the 'replot' proc.

See the comments in those procs for details on how the plotting is implemented by creating a 'gnuplot' script of commands to pass to the 'gnuplot' program.

Although it may sound like stating the obvious, it is probably worth mentioning that the 'listboxSelectionTOexprField' proc is called by a button1-release binding on the listbox --- and the 'replot' proc is called by the 'RePlot' button --- and the 'getset_color' proc is called by the 'Color' buttons.

The 'clear_expr' proc is called by the 'ClearExpr' button, and the 'set_autoscale' proc is called by the 'Autoscale' button.

The 'update_color_button' procs are called near the bottom of the Tk script to initialize the GUI, after initializing some color variables.

And that 'update_color_button' proc is also called in the 'getset_color' proc.

Just a few more comments on some 'features' of this script:

  1. EditInput:

    The 'edit_input' proc is called by the plot procs to check the entries on the GUI --- that they are the proper numeric type, in the proper range, etc.

    If there is an exception, the 'popup_msgVarWithScroll' proc is used to popup a message to the user.

    The 'popup_msgVarWithScroll' proc is also called by the 'Help' button to show the text in the 'HELPtext' variable, which is set at the bottom of the script.

  2. Output Display:

    'gnuplot' typically renders the plot into an output file in a fraction of a second.

    Some 'viewer' variables are used in this Tk script to set the viewer program to use for the various output file types.

    I have set the viewer variables as follows:

    • set GIFviewer "/usr/bin/eog"
    • set PNGviewer "/usr/bin/eog"
    • set JPGviewer "/usr/bin/eog"
    • set PSviewer "/usr/bin/evince"
    • set SVGviewer "/usr/bin/inkscape"

    where 'eog' is the 'Eye of Gnome' image file viewer utility.

    'evince' is a PDF and Postscript file viewer.

    Inkscape is an SVG editor. Inkscape is slow to open.

    It might be just as fast to use a web browser, like Firefox, as the SVG viewer.


Comments in the Code

It is my hope that the copious comments in the code will help Tcl-Tk coding 'newbies' get started in making GUI's like this.

Without the comments, potential young Tcler's might be easily frustrated and be tempted to return to their iPhones and iPads and iPods --- to watch videos of Donald Trump's pursed lips.


The Tcl-Tk CODE

Here is a link to CODE for the script 'tkGnuplot3DsurfaceOr2Dcontour_fromExprFxy.tk'.

You may find it instructive to see the variables set, in an 'Additional GUI Initialization' section near the bottom of the Tk script --- above the setting of the 'HELPtext' variable at the very bottom of the script.

That section is where you can reset the viewers to be used, and change the middle-names and directory locations for the output files (gnuplot script and image files).

The 'HELPtext' variable is set at the bottom of the script so that it can display the values of some of the variables that were set --- for example, the filename that was set for the output 'gnuplot' script file --- and the 'filename-prefix' that was set to be used in creating the name of an output gif/png/jpg/ps/psbw/svg file.

Of course, if you need to change a directory name or want to change a middle-name for these files, you can simply change the 'set' statements that affect those names.


Other 'gnuplot' utilities

This is the third of several 'gnuplot front-end' utilities that I plan to write.

Other Tk 'gnuplot front-end' scripts that may follow are:

  1. bar chart, created from data in a file

  2. points and/or lines xy-plot, created from data entered on the GUI --- for the case of a small number of points to plot, and the user does not want to take the time (or whatever) to put the data in a file

  3. a many-y-values xy-plot, created by selecting many columns of data, say, up to 10, from a text file containing columns of data --- extracting text-strings from the file, strings that are names that can be used for a plot 'key' (legend) for the many lines on the plot.

  4. 2D and 3D plots of selected portions of a 'gnuplot' 'world.data' file --- showing continent (and maybe country) outlines --- in a global or local view --- in spherical or planar (or cylindrical) coordinates.

    (With the 'wxt' terminal output from the 'splot' command, the mouse can be used to rotate a surface plot --- for example, a spherical globe with an outline map on it --- in the 'wxt' terminal window.)


A Sample 'Run':

Here is output from one of my test runs.


This is a screen capture of a 'wxt' terminal image
of a 3D surface plot of the sin(x)*cos(x) function.
This is a full-sized image from which was made
the reduced-size image at the top of this page.

A quite striking feature of the 'wxt' terminal is that it supports 'dynamic rotation' of a gnuplot 'splot' (surface plot) --- so that you are not limited to your initial 3D view setting.

With a mouse, you can rotate the image in both the 'polar' and 'azimuthal' directions --- in other words, you have 'pitch' and 'yaw' capabilities with the 'wxt' terminal.

Here are a few more plots --- done really quickly after the 3D surface plot above.


3D color-shaded surface plot for the
sin(x)*cos(x) function.
This was done after the above hatched-lines
surface plot by simply clicking on the
'Shaded?' checkbutton and clicking 'RePlot'.


2D contour lines plot for the sin(x)*cos(x)
function. I just clicked on the '2Dcontour'
radiobutton and clicked on the 'RePlot' button.

Then I clicked on the 'surface-and-contour' radiobutton and clicked on the 'RePlot' button to get the following plot.


Combined 3D-surface-and-2D-contours plot
for the sin(x)*cos(x) function.

This GUI really speeds up the amount of experimenting per minute that you can do with 'gnuplot' plots.


Sample Color-Spectrum output from
the gnuplot 'test palette' command:

For those who have not seen the output of the 'test palette' command of 'gnuplot', for the default color and 'color-location' values that I have set on the GUI, here is a gnuplot spectrum image. I simply clicked on the 'ShoPalette' button on the GUI.


This is 'gnuplot' 'test palette' output to a
'gnuplot' 'wxt' terminal, because
'terminal wxt persist' was requested.

This screen capture of the 'wxt' terminal window
was done on Linux with the 'gnome-screenshot'
program, to a '.png' file.

Note the sharp change in color from light-blue to green.

This was done by setting the 'location' of light-blue and green on the color spectrum to the same value (25, in a range of 0 to 99).

See the color spectrum settings on the Tk GUI image above.

Here is the gnuplot script that was created when I clicked on the 'ShoPalette' button:


    #!/usr/bin/gnuplot ! cd /tmp set terminal wxt persist title "WXT terminal window" set palette model RGB defined (0 '#0000FF' , 25 '#6464FF' , 25 '#00FF00' , 60 '#C86432' , 99 '#FFFFFF') test palette

In case you did not know, the 'wxt' terminal uses the wxWidgets library, which is where the 'wx' comes from.

The actual drawing is done via Cairo, a 2D graphics library, and Pango, a library for laying out and rendering text.


Future Enhancements:

I have not tested this script extensively.

No doubt, if I use it some more, I will find a few things to change, add, or fix.

I know the GUI is very 'busy-looking'.

See my comments on busy (and extremely non-busy) GUI's, near the bottom of the 'tkGnuplotXY_upto3mathExpressions' page of this site.

I MAY add some descriptions in the comment area on the right of the example functions in the listbox, someday.

And I may replace some of the examples with better ones (in my copious free time --- after I write about 50 other Tk scripts).

I may need to add (or revise) some input checks in the 'edit_input' proc ... someday.

Furthermore, as I point out at the bottom of the 'HELPtext', someday I may try to get more appealing plots --- with color gradient backgrounds --- and better-quality color contour plots --- by using some of the 'gnuplot tricks' of Zoltan Voros, that can be seen at 'www.phyast.pitt.edu/~zov1/' in

In case those pages disappear, here is one of four images from Zotan's contour plots page.

This image shows what Zoltan was able to achieve --- using some tricky 'gnuplot' commands:


A color-gradient-and-contour-lines plot
done by Zoltan with 'gnuplot' commands.

This just goes toward showing :

There is just no end to what can be done, to enhance almost any utility.


Sample gnuplot script:

Here is the gnuplot script file that was created in one of my test runs.

Notice the f(x.y) function near the bottom.


    #!/usr/bin/gnuplot ! cd /tmp set terminal gif size 600 , 600 nocrop noenhanced butt xFFFFFF x000000 x000000 set output '/tmp/${USER}_temp.gif' set title ' PLOT of f(x,y) = sin(x)*cos(y)' set timestamp '%Y %b %d %a %H:%M:%S' set xlabel ' X' set ylabel ' Y' set zlabel ' Z' set xrange [ * : * ] set yrange [ * : * ] set zrange [ * : * ] set xtics rotate by 0 set ytics rotate by 0 set ztics rotate by 0 set nomxtics set nomytics set nomztics set isosamples 100 , 100 set surface set hidden3d trianglepattern 3 set key top right set clabel '%.1f' set view 45 , 45 , 1.0 , 1.0 f(x,y) = sin(x)*cos(y) splot f(x,y) with lines linewidth 1.2 linecolor rgb '#FF0000' ! /usr/bin/eog /tmp/${USER}_temp.gif &

This is pretty crisp and clean, compared to all the comments that I have around the Tcl-Tk code that is writing out these gnuplot commands.


Note that by using the Tk GUI, the user can typically avoid having to page back and forth through 'gnuplot' documentation trying to find commands to use and the proper syntax for those commands --- and which parameters to use with those commands.

And the user avoids many syntax errors, because I filtered out the errors that I made during testing, resulting in gnuplot commands that are probably going to work --- with gnuplot 4.2 and thereafter.

Essentially all of a user's documentation searching and syntax debugging is eliminated by use of this Tk GUI.

Bottom of this web page for
presenting Tcl-Tk code for Tk-GUI
'tkGnuplot3DsurfaceOr2Dcontour_ fromExprFxy'
--- a plot utility in the FE 'tkGooies' system,
in the 'PLOTtools' group.

To return to a previously visited web page location, click on the Back button of your web browser a sufficient number of times. OR, use the History-list option of your web browser.
OR ...

< Go to Top of Page, above. >

Page history:

This FE web page was created 2015 Oct 14.

Page was changed 2019 Mar 05.
(Added css and javascript to try to handle text-size for smartphones, esp. in portrait orientation.)

Page was changed 2019 Jun 24.
(Specified image widths in percents to size the images according to width of the browser window.)


NOTE:
This code and description has not been posted on a Tcler's Wiki page --- at wiki.tcl-lang.org --- formerly wiki.tcl.tk. If I ever do so, I plan to add a link to that page here --- as a backup and alternative to this page.