Chapter 12. Beyond the defaults: workflow and styles

This chapter covers

  • The standard workflow and some variations
  • Using external editors and viewers
  • Hotkeys and mousing
  • Configuring your workspace
  • Defining and using stylesheets

Overall, gnuplot’s defaults are pretty good—so good, in fact, that it’s easy to forget that they aren’t set in stone, and that there may be good reasons for changing them. This applies not only to the visual appearance of plots, but also to the way you interact with gnuplot.

In this chapter, we’ll explore some ways to customize your gnuplot experience. First, we’ll consider workflow alternatives: ways to organize your interaction with gnuplot beyond the regular, interactive session. We’ll discuss various shortcuts and conveniences, along with the possibility of using an external editor for authoring gnuplot command files rather than typing in commands interactively at the gnuplot prompt. Next come various topics that are more typically associated with user customization: custom key (and mouse) bindings, and the definition of private option settings and configurations.

Finally, I’ll introduce the idea of stylesheets: collections of appearance options for lines and points that can be applied to graphs to give them a different appearance. In particular, defining and choosing stylesheets judiciously makes it possible to create graphs with a specific purpose in mind, be it a computer screen, a black-and-white publication, or an overhead presentation.

12.1. The standard interactive workflow

Gnuplot was originally conceived as an interactive tool, and this is still the most natural way to use it: you start an interactive session, enter commands at the gnuplot prompt, examine the resulting graph, and iterate. Frequently, such an interactive session results in a saved command file that can be used to re-create the final state, as well as a final graph, exported in some graphics file format. This section reviews some ideas for improving this straightforward workflow.

12.1.1. Extracting specifics from command files

I’ve pointed out several times before that it isn’t enough to just export the final graph as a PNG or PDF—it’s crucial to also save the final set of options (using save). Only then can you re-create the graph in gnuplot to examine it again, to modify an aspect, or to update it with new data.

The files that the save command generates are long: they contain the values of all of gnuplot’s options,[1] as well as all user-defined functions and variables. Most of this information is redundant: options are written to file even if they still have their default values. The advantage is, of course, that the resulting file is guaranteed to be self-contained. But the information that is specific to the current graph is hard to discern.

1

With three exceptions: the set output, set terminal, and set linetype settings.

You can recover the plot-specific information by comparing the saved file against a file that contains only default values. This baseline file can be obtained by starting gnuplot and—without doing anything else—issuing a save command.

Because the file format of gnuplot’s command files is so simple (line-oriented text files, with one command or option per line), it’s easy to write a short program in your language of choice to compare the two files.[2] Wherever the GNU diff utility is available, it can be used to good effect as well (the cryptic command-line options instruct diff to print only lines that are new or different in the second file):

2

For example, you can find one such program among the contributed scripts on the gnuplot homepage at www.gnuplot.info.

shell> diff --new-line-format="%L" --old-line-format=""
         --unchanged-line-format="" default.gp graph.gp

The resulting file is short and neat, but it’s less self-contained than the original file was, because it doesn’t contain a complete set of options. If the shortened file is loaded into a gnuplot session that’s configured differently from the baseline file, the resulting graph will be different than the original. Also, if gnuplot’s defaults change, the graph created by the shortened file will be affected. This is something to be aware of.

12.1.2. Extending the command set

Sometimes it takes several gnuplot commands to achieve a common task (exporting to file, for instance), sometimes the syntax is awkward and hard to remember (setting up a palette for false-color plots), and sometimes both (time-series scaling for the x axis). It would be nice if we could define our own commands to take the drudgery out of it. There are basically two mechanisms available:

  • Build up a string of commands, and execute it using eval (see section 5.2.2).
  • Capture commands in a command file, and run it using either load or call (see section 11.2.1).

These methods are almost equivalent—the main difference between them lies in the way they’re called. Let’s look at some examples. (Either method can also be bound to a hotkey—see section 12.4.3 later in this chapter.)

Using Scriptlets

It’s important to remember that command files don’t need to be complete: a command file that only defines some functions or sets some options is perfectly legitimate and often useful. Listings 12.1 and 12.2 show two examples that do just that: listing 12.1 defines two distributions that I frequently need in my work; and listing 12.2 switches on time-series mode, using a specific timestamp format. The real benefit of the latter example is that I don’t need to remember the conversion specifiers! (I can never remember whether it’s minutes or months that go with an uppercase M as opposed to a lowercase one.)

You can also collect style definitions and appearance options (line widths and colors) together to form stylesheets. This idea is so important that it’s given its own section (section 12.6) later in this chapter.

Gnuplot looks for scripts invoked with load or call first in the current working directory and then in the directories listed in the loadpath option.[3] The loadpath option can be set using set loadpath; if the GNUPLOT_LIB environment variable is set, its contents are appended to loadpath (see section 12.5.1). It’s therefore possible to create a library of useful scripts in a personal collection.

3

Gnuplot uses loadpath for scripts and also for data: it searches first in the current directory and then in the directories listed in loadpath for data files named in calls to plot or splot.

Listing 12.1. Scriptlet defining common functions (file: normdist.gp)
sqrt2pi = sqrt(2.0*pi)

gauss(x,m,s) = exp(-0.5*((x-m)/s)**2)/(sqrt2pi*s)
lognorm(x,m,s) = exp(-0.5*((log(x)-m)/s)**2)/(sqrt2pi*x*s)

Listing 12.2. Scriptlet to activate time-series mode (file: timeseries-mode.gp)
set xdata time
set xtics format "%T"
set timefmt "%H:%M:%S"
Using Eval

Strings containing valid gnuplot commands can be executed using eval. Furthermore, you can build up strings dynamically for a specific purpose or—even better—write functions to do this for you.

Here’s a simple example. Switching to polar mode usually requires several commands (see section F.2.1). Combining them all into one string, you can achieve the same effect with a single call:

polar = "set polar; set size sq; unset border; unset tics; set rtics; 
set grid polar; set key outside"

Now, eval polar will not only turn on polar mode, but also set up suitable appearance options.

Switching on time-series mode can be accomplished in a similar fashion. If the following strings exist in the current gnuplot session

times = "set xdata time; set xtics format '%T'; set timefmt '%H:%M:%S'"
dates = "set xdata time; set xtics format '%F'; set timefmt '%Y-%m-%d'"

then time-series mode can be turned on by using eval times or eval dates. (Of course, the format of the timestamps in the input file must match the format specified in these strings.)

Finally, and as an example of a function that generates a string dynamically, consider again the export function introduced in section 5.2.2 (see listing 12.3). It generates a string that—when executed using eval—exports a graph, using a user-supplied filename and terminal. The function can be called directly from within the eval command:

eval export( "graph.pdf", "pdfcairo" )
Listing 12.3. A function that generates a command string dynamically (file: export.gp)
export( file, terminal ) = sprintf(
     "set t push; set t %s; set o '%s'; replot; set o; set t pop",
     terminal, file )
Additional Considerations

On startup, gnuplot reads an initialization file (see section 12.5.1), and it may seem natural to place as many definitions as possible in this file so they’re always available. Over time, I’ve moved away from this approach and instead suggest that you use many smaller files, each containing only closely related definitions that can be loaded as needed; this way, you avoid polluting the gnuplot session with all kinds of rarely used functionality.

This highlights one of the main differences between scriptlets and dynamically evaluated strings. The strings (or functions that generate them given a set of arguments) must exist in the gnuplot session, whereas scriptlets don’t. Furthermore, anything that lives in the gnuplot session may be overwritten at any time and without warning; scriptlets, by contrast, offer a degree of encapsulation.

Finally, you can bind either scriptlets or strings to be evaluated with eval to keyboard events. In that case, pressing the appropriate key invokes the desired action. (We’ll discuss this later in this chapter, in section 12.4.3.)

12.1.3. Session variables, loops, and macros

Don’t forget that it’s often possible to streamline your workflow using the techniques introduced in chapter 5: session variables, string macros, and inline loops. Inline loops don’t need any further explanation (you’ve seen plenty of examples), but here are some ideas for using session variables and macros.

Using Variables

Imagine that you want to work with a data set that’s in a file with an inconveniently long filename (possibly not even in the current directory). Assigning the name to a variable helps to keep command lines much shorter:

FILE = "../path/to/directory/long-and-painful-filename.dat"
stats FILE u 2 nooutput
plot FILE u 1:($2/STATS_mean) w lp

Another possibility is to assign just the base name of the file to a variable, and add extensions on the fly:

BASE = "long-and-painful-filename"

plot BASE . ".dat" u 1:2

save BASE . ".gp"

set terminal pdfcairo
set output BASE . ".pdf"
replot

You get the idea.

Using Macros

Macros are another way to shorten command lines (see section 5.2). Imagine that you want to plot several files using the with xyerrorbars style. That style requires six columns to be named in the using clause. A macro may come in handy:

cols = "using 1:2:3:4:5:6"
plot "data1" @cols w xyerrorbars, "data2" @cols w xyerrobars

In fact, you could make with xyerrorbars part of the macro! Macros can also help straighten out complicated inline transformations:

trsf = "using ($1-$2/$3):(sqrt((abs($4-$5)/$6)))"
plot "data1" @trsf, "data2" @trsf

A third idea is to use macros to shorten appearance options, in particular colors (see section 9.1). Compare this command

plot "data" u 1:2 lc rgb "red", "" u 1:3 lc rgb "green",
  "" u 1:4 lc rgb "blue"

with this:

r = "lc rgb 'red'"
g = "lc rgb 'green'"
b = "lc rgb 'blue'"

plot "data" u 1:2 @r, "" u 1:3 @g, "" u 1:4 @b

Defining line styles is an alternative, of course.

12.2. Using external editors and viewers

In everything so far, I’ve assumed that you’re using gnuplot interactively: that you started gnuplot and are typing commands at gnuplot’s own command prompt and that you view the generated plots in one of gnuplot’s interactive terminals (such as the wxt or qt terminal). But it turns out there are other ways to interact with gnuplot, even for interactive, non-batch work. (Batch-oriented operations are treated in chapter 11.)

Rather than entering commands at gnuplot’s prompt, you may find it convenient to use your favorite text editor to type commands into a command file and then let gnuplot run this file as a script. One way to do this is to run an interactive gnuplot session in another window.[4] You then load the script using load and examine the graph in one of the interactive terminals.

4

Depending on your text editor, you may not even need a separate window. If you use Emacs, for instance, an internet search will turn up not one, but two gnuplot modes that let you run gnuplot from within your Emacs window.

Alternatively, you may choose to work with one of the file-based terminals and export graphs in PNG or PDF format directly. If you do this, you need to specify the output terminal and filename in your script before the plot command:

set terminal pdfcairo
set output "graph.pdf"
plot sin(x)

Now you don’t even need to start an interactive session. Instead, you run gnuplot at the shell prompt, giving the name of your script as a command-line argument to gnuplot

shell> gnuplot script.gp

and view the resulting graph in a separate viewer (such as okular or evince). Modern viewers usually detect when the file they’re displaying changes on disk; they automatically reload and redisplay the graph after you change your script and run gnuplot again, leading to a comfortable workflow experience.

Alternatively, you can load the command file into a gnuplot session using load, but in this case your script must contain the command set output after the plot command to ensure that all output buffers are flushed. Running gnuplot from the shell prompt avoids this need: the gnuplot process terminates after completion of the script, and that forces all open files to be flushed.

Using an external editor (and, possibly, an external viewer) has some advantages compared to running gnuplot in an interactive session:

  • All commands and option values are simultaneously visible in the command file.
  • Editing may be more convenient in a proper editor.
  • You can never forget to save your commands (not just your graph).
  • For file-based formats, there can be no discrepancy between the appearance of the graph during the interactive session and the final graph saved to disk. (This can be a problem when you prepare a graph using an interactive terminal but then export the final version as PNG or PDF.)
  • Because multiplot mode (see section E.1) doesn’t permit you to change the output and terminal settings, the command-file-based approach is the only practical way to create a multiplot graph.

The primary disadvantage of using an external editor is the need to run a separate window (which can be mitigated if a gnuplot plug-in is available for your editor). When using file-based output formats and external viewers, you lose the ability to interact with the graph using the mouse—which often doesn’t matter but can be painful at times.

Tip

Consider using an external editor and viewer. You might like it!

12.3. Invoking shell commands from gnuplot

Gnuplot can’t do everything alone. It’s occasionally useful to invoke other programs within a gnuplot session. There are four ways to do this:

  • The system command executes a command in a subshell, directing its output to the interactive gnuplot terminal. For example, you can list the contents of the current directory with system "ls".
  • The system() function is similar to the system command. It takes a command as argument, executes it as a subprocess, and returns its output as a string (in contrast to the system command, which always directs any output from the subprocess to the interactive terminal).
  • Backticks or back quotes (decimal ASCII code 96—typically bound to the leftmost key in the top row on the keyboard) may be familiar from Perl and some Unix shells. The command in back quotes is executed, and its output replaces the back-quoted text (including the back quotes). Back-quote substitution can be used anywhere except inside single-quoted strings.
  • The shell command suspends the current gnuplot session and starts an interactive shell. Quitting the shell (typically by typing exit or pressing Ctrl-D) resumes the gnuplot session. (The shell command is somewhat of a legacy from days before windowing systems—today, we’re more likely to pop up a shell in another terminal window, rather than suspend the process in the current window.)

In general, the system() function is more versatile than backticks and is the preferred way to capture output from a subprocess. But backticks have the advantage that they can occur inside double-quoted strings, whereas the output from the system() function must be concatenated explicitly to the string. In other words, the following two commands are equivalent:

set label 1 "Today: `date`" at 0,0
set label 2 "Today: " . system( "date" ) at 0,1

For simple string substitutions such as these, backticks can be a convenient shorthand. For more complicated operations, the system() function is the better choice.

12.3.1. Worked example: plotting each file in a directory

Shell commands can be combined with loops. To plot every file in the current directory, either of the following two commands will work:

12.4. Hotkeys and mousing

When you issue a plot command, gnuplot pops up a new window containing the plot (assuming, of course, that you’re working with one of the interactive terminals and not currently exporting graphs to file). The new window containing the graph is automatically raised or active.

When a graphics window is active like this, you can invoke gnuplot commands through keyboard shortcuts or mouse clicks. In this section, we look at some of the default bindings provided by gnuplot, and also see how to define custom keyboard or mouse shortcuts.

12.4.1. Default hotkeys

Pressing the space bar when the plot window is active raises the gnuplot command window. This is convenient when you’re doing interactive work: you can iteratively continue working on a single graph without ever having to take your hands off the keyboard!

Grid lines can be toggled on or off through the hotkey g. Logarithmic plotting is bound to l (y axis only) and L (in this case, gnuplot scales only the axis closest to the mouse pointer logarithmically). The + and - keys can be used to zoom in and out of the plot. Pressing q closes the current plot window.

These and some other interesting default bindings are listed in table 12.1. You can get a display of all currently defined key bindings by pressing h while the plot window is active.

Table 12.1. Selected default hotkey bindings

Key

Function

Space bar Raises the command window and switches keyboard focus to it
q Closes the current plot window
g Toggles grid lines on the plot
r Toggles the crosshair (ruler) at the current mouse position
l (lowercase letter L) Toggles logarithmic scaling for the y axis
L Toggles logarithmic scaling for the axis closest to the mouse pointer
+ Zooms in
- Zooms out
u Unzooms (after zooming using the mouse)
h Help: shows all key bindings
Arrow keys Scrolls the graph in the indicated direction

I don’t find most of the default bindings all that useful (and some are outright annoying), but custom hotkeys (see section 12.4.3) can be very useful indeed.

12.4.2. Mousing

In interactive terminals, you can use the mouse to navigate the graph. By default, mouse actions should be enabled, but in case they aren’t, you can enable them using the command

set mouse

When the mouse is active, the current coordinates are always displayed at the bottom of the plot window. You can place a temporary crosshair at the current mouse position by pressing the r key. Pressing r again switches off the crosshair. While the crosshair is active, its location and the relative distance of the mouse pointer from the crosshair coordinate are shown in the plot window, together with the absolute coordinates of the mouse pointer.

You can use the mouse to zoom in on a graph by dragging the mouse while holding mouse button 3 (often the right mouse button). Click into the graph with mouse button 3, drag while holding the button down, and then click with mouse button 1 to replot only the section of the graph in the indicated region. Press u (unzoom) to return to the previous setting. When you use the mouse to set the plot range in this way, both the x and the y range are fixed according to the mouse coordinates (in particular, the y range is no longer autoscaled).

There are other ways to use the mouse in current interactive terminals. For example, clicking a key entry toggles the corresponding curve in the graph on or off.[5] The set mouse command takes some additional options that mostly control the display format of the mouse coordinates in the plot window. Check the standard gnuplot reference for details.

5

This feature is new with gnuplot 5.

12.4.3. Custom hotkeys

The standard hotkey bindings are nothing to write home about, and neither is the default mouse behavior. But you can also define your own hotkey and mouse bindings, and that allows for some exciting possibilities.

The bind command is the essential facility to do this. It’s used to bind gnuplot commands to key strokes or mouse clicks. Here’s a trivial example:

bind "r" "replot"

This binds the r key to the replot command. Now, pressing the r key (while the plot window has focus) will redraw the most recent plot.

The Bind Command in Detail

The bind command takes two string arguments: the key (possibly in combination with one or several of the control keys) and the command to be executed (when invoked without arguments, bind shows all currently defined bindings):

You can bind commands to special keys—see table 12.2 for the symbolic names of some function keys you may want to know, and see the standard gnuplot reference documentation for the bind command for the complete list.

Table 12.2. Symbolic names of some of the function keys available

Location

Name

Control keys "ctrl-", "alt-"
Main key block "Tab", "Escape", "Return"
Arrow keys "Left", "Up", "Down", "Right"
System key block "Home", "End", "PageUp", "PageDown"
Function keys "F1", ..., "F12"
Window events "Button1", "Close"

Usually, the commands bound to the hotkeys are executed only if the plot window has keyboard focus; hotkeys don’t apply when the command window has focus. This behavior can be overridden by the optional allwindows option to bind: if it has been given, then the binding applies to all plot windows, active or not. In this case, the variable MOUSE_KEY_WINDOW is set to the ID of the window generating the event.

Here are some additional points to watch out for:

  • Neither the space bar nor the q key can be rebound from its default settings.
  • Only mouse button 1 can be bound.
  • Running bind without arguments displays a list of current bindings. So does show bind or pressing the h key while the plot window has focus.
  • The command reset bind returns all key bindings to their defaults.
Worked Examples

Some of the custom additions to the standard command set that were discussed in section 12.1.2 can be bound to keys. Assuming that the string variables polar, times, and dates exist in the gnuplot session and have the values shown earlier, you can bind them to keys, like so:

bind "F1" polar
bind "F2" times
bind "F3" dates
bind "F4" "reset session"

For convenience, I’ve bound these commands to function keys here; you can bind them to any other key as well. The binding for F4 resets gnuplot to its state at the beginning of the session, presumably resetting the configuration changes brought about by any of the other keys.

You can also bind the loading of a scriptlet to a key. In this case, the effective command is load:

bind "F5" "load 'normdist.gp'"

One word of warning: if you use string variables in bind (as in the bindings for F1, F2, and F3 in the earlier example), then the variables must contain the string to evaluate at the time the bind command is executed (early binding). You can’t bind a key to a variable first and then dynamically change the value of that variable later.

12.4.4. Capturing mouse events

Whenever a mouse or keyboard event occurs while the graph window has focus (and provided mousing is enabled using set mouse), gnuplot populates several variables with information regarding the details of the most recent events. The names of these variables all begin with the prefix MOUSE_. See table 12.3 for a complete list.

Table 12.3. These variables are set whenever a mouse or keyboard event occurs when a plot window is active, provided that mousing has been enabled using set mouse.

Variable name

Description

MOUSE_X x coordinate at the time of the mouse event (measured in the first coordinate system)
MOUSE_Y y coordinate
MOUSE_X2 x coordinate (measured in the second coordinate system)
MOUSE_Y2 y coordinate
MOUSE_BUTTON ID of the mouse button clicked (1, 2, or 3)
MOUSE_SHIFT Nonzero if the Shift key was pressed when the event occurred
MOUSE_CTRL Nonzero if the Ctrl key was pressed when the event occurred
MOUSE_ALT Nonzero if the Alt (Meta) key was pressed when the event occurred
MOUSE_KEY ASCII code of the key that was pressed
MOUSE_CHAR Character value of the key that was pressed
MOUSE_KEY_WINDOW ID of the plot window that received the event

You can use the information contained in these variables, in combination with the bind command, to write gnuplot code that responds to user actions. In this way, it’s possible to achieve a limited form of programmable interactivity.

Worked Example

Here’s an intentionally simple example, mostly to demonstrate the principle. I’ll present a much more interesting and useful application in the following section.

If you execute the following command

bind "Button1" "set label at MOUSE_X, MOUSE_Y center point pt 1 ps 4; 
set label at MOUSE_X, MOUSE_Y center point pt 6 ps 3; replot"

and then click into the plot window, a point symbol is placed at the current mouse position—for example, to draw attention to an oddity in the data. To make things a little more interesting, it’s a symbol that gnuplot doesn’t provide as a built-in: a crosshair, here generated from a separately drawn cross and circle. To remove the symbols, you need to find their tags first using show label and then remove them individually with unset label, followed by the tag.

This code snippet is a straightforward application of the bind command. Let me draw your attention to the replot command at the end of the command string: this is common practice when using bind and ensures that the result of the action is visible immediately. You’ll see more examples of this technique in the next section.

12.4.5. Case study: placing arrows and labels with the mouse

Truth be told, I don’t find most key bindings terribly useful: the whole purpose of gnuplot is graphs, and I want to interact with them using the mouse, not the keyboard (for a stunning exception to this rule, see section D.7). Fortunately, the bind command can be used to create some special mouse bindings as well.

Wouldn’t it be nice if you could place arrows and labels onto the graph with the mouse: just point and click? Turns out you can. Here are some ideas.

Labels

The problem with placing labels is that there isn’t a way to prompt the user for the text of the label. Hence, you must rely on the user to prepopulate an agreed-on variable, or you must rely on the user to call an appropriate function later.

The following snippet follows the former approach:

bind "ctrl-Button1" 'eval sprintf( "set label %d "%s" at %f,%f; replot", 
labeltag, labeltext, MOUSE_X, MOUSE_Y )'

It assumes that the variables labeltext and labeltag have been populated appropriately. Then, clicking into the plot while pressing the Ctrl key will place the label at the current position of the mouse pointer.

Two notes on implementation: in the second argument to bind, you must escape the innermost quotation marks. Also note the replot command, which ensures that the plot automatically updates when the mouse button is clicked. This is common practice when using bind.

The next code snippet takes the other approach. You click first, and then you supply the text (note that the second string supplied to the bind command is continued on the next line):

bind "ctrl-Button1" "label_x=MOUSE_X; label_y=MOUSE_Y; 
set label 1000 at label_x,label_y point; replot"

label( tag, text ) =
  sprintf( "set label %d '%s' at %f,%f; unset label 1000; replot",
           tag, text, label_x, label_y )

Now, if you Ctrl-click anywhere in the plot window, a point symbol is placed at the position of the mouse cursor, to remind you to supply the label text. You do the latter using the label() function, which removes the point from the graph and replaces it with the supplied text. Don’t forget to use eval with this function:

eval label( 2, "Hello, World!" )
Arrows

Arrows are trickier, because you need to capture two positions. The problem is that the only accessible mouse event is the click: this means you can’t use drag-and-drop as in a drawing program. Instead, you have to capture two clicks separately. This leads to a problem: what if you change your mind between the first click and the second?

Listing 12.4 shows the solution. You bind both the mouse click and the Esc key. When the mouse key is clicked once, a temporary marker is placed on the plot; when a second click occurs, the marker is removed and an arrow is drawn. If you change your mind after the first click, you can press the Esc key, which removes the temporary marker and leaves gnuplot in a clean state. Pretty cool! (Try it!)

Listing 12.4. Commands to place arrows using the mouse (file: mouse-arrows.gp)
bind "Button1" 
"if(exists('arrow')==0) { 
   arrow=1; arrow_x=MOUSE_X; arrow_y=MOUSE_Y; 
   set label 1000 at arrow_x,arrow_y point; replot; 
 } else { 
   unset label 1000; 
   set arrow from arrow_x,arrow_y to MOUSE_X, MOUSE_Y; replot; 
   undefine arrow,arrow_x,arrow_y 
}"

bind "Escape" "unset label 1000; replot; undefine arrow,arrow_x,arrow_y"

A crucial element of the logic in listing 12.4 is the variable called arrow. If it exists in the gnuplot session, then you know the first point has been selected and the temporary marker has been placed; if it doesn’t exist, then the first point has not been selected yet. You can test for the existence of a variable with this name using the exists() function. The reason to test for the existence of this variable (rather than for its value) is that a test for value would result in an error if the variable hadn’t yet been initialized. The existence test is more robust.

Tip

The snippet in listing 12.4 works extremely well. It takes all the pain out of gnuplot’s set arrow facility.

12.5. Startup configurations and initialization

You can pass commands and information to gnuplot on startup. All three typical ways of initializing a program are available: initialization files, environment variables, and command-line flags. Let’s consider them in turn.

12.5.1. Startup and initialization files

On startup, gnuplot attempts to read the file gnuplotrc from a standard location, such as /usr/share/gnuplot/ on Linux—run show loadpath to see the configured location. By default, this file is empty, but you can use it for customizations that should be global to your installation.

Gnuplot also looks for a personal initialization file, called .gnuplot on Unix (and Mac OS) and GNUPLOT.INI on Windows. Gnuplot searches for this file first in the current directory and then in the current user’s home directory (as defined by the corresponding environment variable). Once a file has been located, searching doesn’t continue. The file is executed (using load) before any other files or commands are read from the command line, standard input, or an interactive terminal. In general, settings in the initialization file override environment variables.

You can suppress reading of both initialization files by giving the -d command-line option when invoking gnuplot. This may be useful when you want all of gnuplot’s internal settings to assume their default values.

What to Put in Your Initialization File

I recommend keeping the default initialization file relatively short, in order to prevent pollution of the gnuplot session (and all command files subsequently saved with save). I think it’s a better idea to group related settings in individual command files that can be loaded as needed, and to limit the default file to only those settings that you really want to have in effect at all times. Also keep in mind that there is only one initialization file that is read automatically by gnuplot. With individual command files or stylesheets (see section 12.6), you have greater control over the state of your gnuplot session. (You can either load them after gnuplot has started, using load, or specify them on the command line.)

The following listing shows my personal initialization file. It’s relatively short and contains only a handful of settings that I find generally useful.

Listing 12.5. A typical .gnuplot initialization file (file: dot.gnuplot)

The first few lines fix instances where gnuplot’s defaults don’t work well . I explicitly enable UTF-8 (see the sidebar at the end of section 5.1) and increase the sampling density for plot and splot (see sections 3.1 and C.1.2). Next, I define the path for my local library of gnuplot scripts and load the default style sheet directly from that directory . Then I define two functions for handling color (see section 9.1.1) and define bindings that let me set arrows with the mouse (see listing 12.4) . That’s it—everything else is loaded only as required.

12.5.2. Environment variables

Gnuplot examines several environment variables (see table 12.4). Not all of them are still important; some of them provide information for graphics terminals that are no longer current. In general, I don’t like to rely on environment variables and instead prefer explicit initialization in a configuration file or scriptlet.

Table 12.4. The environment variables that gnuplot reads on startup. Unless otherwise specified, the variables have the same name on all platforms.

Name (Unix and Mac OS X)

Name (Windows, if different)

Description

GNUTERM   Name of the terminal to be used. (Compare the set terminal command.)
GNUHELP   Path to the online help file gnuplot.gih.
GNUPLOT_LIB   Additional directories to be searched for data and command files. (Compare the set loadpath facility.)[a]
GDFONTPATH and GNUPLOT_DEFAULT_GDFONT   Search path used by terminals based on the GD library (PNG, GIF, and JPG) to locate font files, and a default font to be used with these terminals, respectively.
GNUPLOT_FONTPATH   Search path used by the PostScript and SVG terminals to locate font files. (Compare gnuplot’s set fontpath facility.)[a]
GNUPLOT_PS_DIR   Used by the PostScript terminal to locate custom prologue files.
GNUFITLOG   Name of the log file maintained by the fit command (discussed in section F.7); defaults to fit.log. If a directory is named, then gnuplot creates a file with the default name in this directory.
HOME GNUPLOT and USERPROFILE Directory to search for a .gnuplot initialization script if none is found in the current directory.
PAGER n/a Name of the pager program to use.
SHELL COMSPEC Name of the shell to spawn in response to the gnuplot shell command.

a

Path entries are separated from one another using a colon (:) on Unix and a semicolon (;) on Windows.

12.5.3. Gnuplot command-line flags

In general, gnuplot executes the contents of command files named on the command line when gnuplot is first started (see section 11.3). Remember that the special filename - (hyphen) suspends processing of the command line and begins reading interactive commands from standard input.

In addition, gnuplot recognizes six command-line flags. See table 12.5.

Table 12.5. Command-line options recognized by gnuplot

Short form

Long form

Description

-V --version Prints version information.
-h --help Prints a short usage message.
-p --persist Continues to display the display window for interactive terminals, even after the interactive gnuplot session has terminated.
-d --default-settings Suppresses loading of both the global (gnuplotrc) and the personal (.gnuplot) initialization files.
-c ...   Treats the rest of the command line as if invoked using call. This option should be followed by the name of a command file and, optionally, its arguments.
-e "..."   Executes the commands given as string argument before processing the rest of the command line.

12.6. Stylesheets

The concept of a stylesheet is probably most familiar in the context of web development, but it is, in fact, more general: wherever a document is prepared using markup, the stylesheet principle can be applied. The markup language is used to indicate semantics, whereupon the stylesheet is applied to fix the visual appearance.

This notion can be carried over to gnuplot, once you realize that a command like

plot "data" u 1:2 w lp lt 1, "" u 1:3 w l lt 2

constitutes a form of markup. The appearance of the plot depends on the styles that are in effect when the plot is rendered by gnuplot. By supplying suitably chosen definitions for line types and other properties (such as arrow styles and text fonts), you can therefore create a family of graphs, each with a different visual appearance.

The notion of using stylesheets like this with gnuplot may seem unfamiliar (at least, I’ve never seen this done before), but it’s an extremely powerful concept. It enables you to create graphics for specific circumstances and purposes. At their most basic, stylesheets allow you to create both color and black-and-white versions of graphs, but the idea can be taken further. Graphs for interactive work (on a computer screen) place different demands on colors, line widths, point sizes, and so on, than graphs prepared for (say) a PowerPoint presentation (see the sidebar “But is it beautiful?” later in this chapter).

To be clear, I’m not saying you can apply a different stylesheet to an existing command file and obtain a satisfactory graph without tweaking (as you can with CSS or, for example, LaTeX). But by using different sets of predefined line types and other visual-appearance options, you can begin to create graphs that take the specifics of the intended presentation channel or medium (screen, print, or overhead) into account. If nothing else, you can use a personal stylesheet to escape the standard look of gnuplot graphics (although I don’t think you should—see the sidebar in section 8.3.2). But it’s nice to have the option!

Tip

Customize styles to adapt the appearance of graphs to their intended use and medium. Collect related styles together to create stylesheets for different purposes.

12.6.1. Worked example: stylesheets

What does the stylesheet concept look like in practice? In this section, I’ll present the same graph four different ways, using four different stylesheets—with no changes to the plot command! The plot includes six curves (so there’s a need for a variety of distinguishable line styles) and both sparse and dense data sets (so I have the opportunity to use both the with lines and the with linespoints plot styles).

The plot command is shown in the next listing. It’s used without modification to generate all of the next four graphs. Only the stylesheets differ.

Listing 12.6. Plot command for figures 12.1 through 12.4 (file: style-cmd.gp)
set xlabel "Input"
set ylabel "Response"

plot "sparse" u 1:2 t "Sparse 1" w lp, "" u 1:3 t "Sparse 2" w lp,
  "" u 1:2:(1000) t "Smooth" s acs w l,
  "dense" u 1:2 t "Dense 1" w l, "" u 1:3 t "Dense 2" w l,
  "" u 1:4 t "Dense 3" w l

The stylesheets must be loaded (using load) before the plot command is issued. You should also run reset or reset session before loading the next stylesheet (otherwise, previous styles will sometimes interfere with current ones).

Interactive Computer Work 1: Thin and Bright

The stylesheet in listing 12.7 is intended as a replacement for the old gnuplot default appearance and is meant primarily for interactive use at a computer screen (although I also used it for most of the color figures in this book). It’s characterized by relatively thin lines, in bright colors. To make thin lines visually distinguishable, it’s necessary to choose relatively bright colors; but in contrast to the old gnuplot default, the colors are toned down a bit. A dark green is used in place of bright green, and the color yellow (traditionally the sixth style in the default sequence), which is too difficult to see against a white background, is replaced with a drab goldenrod.[6] Moreover, I tried to make sure colors that are adjacent in the sequence exhibit good contrast with each other; hence the two greens and blues are well separated. The choice of point type also warrants a remark: instead of the spidery cross and saltire, this stylesheet prefers filled and open circles and squares. The resulting plot is shown in figure 12.1. (The set termoption command changes just one aspect of a terminal, without requiring the terminal to be specified—see chapter 10.)

6

Because hex strings aren’t intuitive, the X11 color name has been included for each stylesheet color in this section.

Figure 12.1. The example graph using the stylesheet from listing 12.7: thin lines, bright colors, small symbols

Listing 12.7. Stylesheet for figure 12.1 (file: style1.gp)

Interactive Computer Work 2: Thick and Pastel

The second stylesheet (listing 12.8) is also intended for interactive use on a computer screen, but behold how different the resulting graph appears! (See figure 12.2.) Gone are the brightly colored hairlines, and instead the graph uses thick, wide lines in soft pastel colors. (It also uses a boldface font, in keeping with the thick line widths.) If you’re used to graphs like figure 12.1, then this style takes some getting used to, but I recommend that you give it a fair try. After a while, you may notice that the muted colors and soft edges have a welcome, soothing effect. But it’s quite different than what you saw before.

Figure 12.2. The example graph using the stylesheet from listing 12.8: thick lines, pastel colors. Compare figure 12.1.

Listing 12.8. Stylesheet for figure 12.2 (file: style2.gp)

Print Publishing: Black-and-White

For print publishing, it may still be necessary to submit graphs in black and white. For line art, this means you have to resort to dash patterns to distinguish lines from each other. This is what the stylesheet in listing 12.9 is for. It uses custom dash patterns that are intended to re-create (and improve on) the dash patterns from gnuplot’s PostScript terminal. In keeping with the preference for hairlines in scientific drawing, it doesn’t use filled point symbols and instead gives preference specifically to the cross and saltire—but with a twist! It uses gnuplot’s new pointintervalbox feature so the continuous line doesn’t touch, and thereby interfere with, the point symbols. The resulting graph is shown in figure 12.3.

Figure 12.3. The example graph using the stylesheet from listing 12.9: black-and-white, dashed hairlines, cross-shaped symbols

Listing 12.9. Stylesheet for figure 12.3 (file: style3.gp)
set linetype 1 pi -1 pt 1 lc black dt solid
set linetype 2 pi -1 pt 2 lc black dt (8,6)
set linetype 3 pi -1 pt 6 lc black dt (4,3)
set linetype 4 pi -1 pt 4 lc black dt (3,6)
set linetype 5 pi -1 pt 1 lc black dt (12,5,2,5,2,5)
set linetype 6 pi -1 pt 2 lc black dt (16,8)
set linetype 7 pi -1 pt 6 lc black dt (20,6,2,6)
set linetype 8 pi -1 pt 4 lc black dt (30,10)

set pointsize 0.5
set pointintervalbox 1.75

set termoption font "Helvetica,12"
set termoption fontscale 0.5
A Walk on the Wild Side

The last stylesheet has a two-fold purpose: I want to demonstrate some intentionally questionable choices for the appearance of a graph—these aren’t recommendations! More seriously, I also want to show how to make a graph look entirely different from the usual gnuplot appearance. Here are some of the differences: the graph has no frame, but a couple of arrows indicating the coordinate axes; the aspect ratio is square; the font is a serif type; the lines are wide and bright; despite being color-coded, they’re also dashed; the frame around the key unnecessarily clutters and partially obscures the graph; and the text is either too large or too small. Not all of these choices are poor, but some definitely are. (See the following listing and figure 12.4.)

Figure 12.4. The example graph using the stylesheet from listing 12.10: as different from the gnuplot defaults as possible

Listing 12.10. Stylesheet for figure 12.4 (file: style4.gp)

But is it beautiful?

Gnuplot’s defaults owe some to scientific tradition and some to technical limitations on early computer systems. Few of these limitations still remain, which means you’re free to choose from the available options for the best results.

The first two of gnuplot’s point symbols (or point types—see figure 9.7) come from a scientific tradition: on graph paper, where accuracy needed to be maintained manually, two thin, short lines intersecting in a point provided a good way to fix a location on the graph precisely. Today, when the data is available numerically and the computer takes care of accuracy, this is much less of a concern, and you can choose symbols that are more aesthetically pleasing.

For scientific plots of medium-sized data sets, both cross and saltire may still be adequate. The combination of the two (the third symbol in gnuplot’s default ordering) is bulky and shouldn’t be used.

For presentation graphics, in particular for sparse data sets, I recommend the filled circle and the filled square. These two symbols, together with a choice of colors, should be enough to distinguish several data sets in a single graph. If you need even more symbols, I recommend the unfilled circle and unfilled square, followed by cross and saltire, and possibly the tip-down triangles (filled and unfilled). The diamond (four-cornered symbol, standing on its tip) doesn’t reproduce well and should probably, although regretfully, be avoided.

For large data sets consisting of many points, the unfilled circle has a special advantage: even if points are spaced densely enough that symbols overlap partially, unfilled circles provide the best chance of being recognizable as separate symbols. Whereas filled symbols occlude each other, and symbols made up of straight lines (such as crosses and squares) blend together as individual edges align, unfilled circles can still be distinguished from each other.

Traditionally, thin lines have been used in scientific publishing: again, because a thin line fixes a location on a graph more precisely. This is still a good tradition to follow, in particular for print publishing: thin lines often give a publication a classy appearance. (Provided they aren’t too thin to render properly—as publishers switch from photo-offset to print-on-demand technology, sturdier lines might be a good idea!)

For other publication channels, this isn’t true. In particular for slides and overhead presentations, thicker, rounded lines work better: they can be seen from the back of the room, and they tend to fit better with the overall style of the medium. Graphs for the Web fall between these two extremes.

In general, I recommend using non-serif fonts (such as Helvetica) for labels on a graph, because such fonts are the most neutral. Make sure you choose the font size properly: it’s surprisingly common to see graph labels that are too large, leading to an imbalanced appearance of the entire graph.

12.7. Summary

In this chapter, we explored different ways to go beyond gnuplot’s default appearance and behavior. First, we considered ways to streamline your gnuplot workflow through scripts and customized key bindings (hotkeys). You may want to personalize your work environment when using gnuplot, and I showed you how to do that.

In the last part of the chapter, I introduced the concept of stylesheets. Stylesheets are bundles of appearance options that you can use to create graphs that are optimized for their intended use and medium—be it an interactive computer session, a black-and-white print publication, or a presentation to a live audience.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.128.105