Chapter 10. Terminals and output formats

This chapter covers

  • Understanding terminals
  • Font selection and enhanced text mode
  • Standard graphics file formats
  • Mathematical formulas with gnuplot and LaTeX
  • Interactive terminals

Gnuplot can generate graphs in all common graphics formats (and some uncommon ones, too). The components within gnuplot that are ultimately responsible for creating all graphical output are called terminals. Different output formats require different terminals.

Because terminals are the final step in the creation of a graph, the ultimate appearance of a graph depends directly on the capabilities of the terminal used to generate it. Some of gnuplot’s terminals produce output of very high quality and are among gnuplot’s primary assets. Unfortunately, terminal handling in gnuplot is a bit different than comparable functionality in other programs. We’ll therefore begin our discussion of terminals with a brief historical digression that explains the motivation behind gnuplot’s terminal abstraction.

An important capability that is provided by each terminal is the handling of fonts or typefaces: the selection of fonts and the available effects (italics, boldface, sub- and superscript) are determined by the choice of terminal. So, we’ll discuss fonts and related topics in this chapter as well.

Next, we’ll examine the most important terminals, beginning with terminals that generate output in standard graphics file formats (specifically, PDF and PNG). Then we’ll talk about ways to include mathematical notation and formulas on graphs, with and without the use of LaTeX. We’ll introduce gnuplot’s svg and canvas terminals, which generate graphics suitable for viewing in contemporary web browsers. And finally, we’ll quickly survey gnuplot’s interactive terminals.

10.1. The terminal abstraction

If you look in the standard gnuplot reference documentation, you’ll find that gnuplot supports some 70 different terminals! This may seem daunting, but the reality is that most of them are obsolete today—the number of terminals that are relevant is (thankfully) much smaller. But this leaves unanswered the question of where these 70 different terminals originally came from. For this, we need a bit of history.

10.1.1. Historical digression

Gnuplot was originally conceived and implemented at a time (the late 1980s!) when graphics support was much less standardized than it is today. It wasn’t safe to assume that a computer even had an interactive graphics terminal: producing graphics usually required special hardware (such as an attached pen-and-ink plotter or a dedicated graphics display).

The generic name for such a device that produced visible output was terminal. To keep gnuplot portable, all code specific to a single terminal was encapsulated into the terminal facility—today, we’d call it the terminal driver. As graphic terminals developed and proliferated, gnuplot acquired a selection of such drivers. Nowadays, many of these legacy devices are obsolete, but the drivers are still part of the gnuplot distribution. Most of them can safely be ignored.

Nevertheless, the abstraction has proven itself capable of adapting to changing circumstances. Today, the established architecture supports the two forms of graphical output that are still relevant: it drives interactive, screen-based displays (interactive terminals such as the wxt and qt terminals), and it creates output files, using any of a variety of standard graphics formats and command languages.

10.1.2. The terminal workflow

The primary reason terminal handling is often seen as obscure and confusing is that it requires multiple steps. Moreover, if the sequence of steps is interrupted, the gnuplot session may end up in a different state than at the beginning. This is confusing, because the near-unequivocal behavior of most contemporary programs is that an action “export to file” is both atomic and stateless (or, at least, it appears to be). In other words, you usually issue a single command to create a file, and then you’re right back to where you started. Not so in gnuplot.

The Standard Workflow

The complete workflow to create a graphics file from an interactive gnuplot session and to restore the interactive session again consists of the following six steps (also compare listing 2.2):

1.  Save the current state of the terminal option with set terminal push.

2.  Select a new terminal using set terminal.

3.  Select the desired output file or channel name with set output.

4.  Generate a plot using plot, splot, replot, or refresh.

5.  Restore the original terminal setting using set terminal pop.

6.  Restore the original file or channel name with set output.

One reason for this multistep process is that the same terminal abstraction is used for both the interactive session display as well as the printable export, requiring you to switch between different modes in a way that seems cumbersome today.

Two issues in particular tend to trip up the unwary. The first is the need to choose the file format (via the terminal) and the desired filename through two separate commands (set terminal and set output). The second is the requirement to restore the interactive session explicitly after the output file has been generated. (If this doesn’t happen, subsequent plot commands continue to be sent to the file, clobbering its contents.)

Some day, gnuplot will acquire an export command that will perform all the required steps automatically. Until then, you have to either make sure to complete all the necessary steps manually or use a macro of some form. (You can find implementations of macros for this purpose in sections 5.2.2, 11.2.1, 11.2.2, and 12.1.2.)

Tip

To export a plot to a file from an interactive session requires multiple steps. Make sure you complete the process manually or use a macro.

Flush Your Buffers!

As it turns out, there is a particularly nasty third problem, which is that output buffers aren’t necessarily flushed after a plot (or equivalent) command. This means when the plot (or equivalent) command returns, the output file may still be incomplete and not yet ready to be used as input to other programs.

There’s a simple remedy, though: the next set terminal or set output command is guaranteed to complete the output file and flush any open buffers. Hence, even if you don’t want to resume your interactive session, you still need to issue either a set output or set terminal command. Also be aware that quitting gnuplot does not necessarily flush open files!

Tip

Output files may not be complete even after the plot command returns. To guarantee that all buffers are flushed and the file is completed and closed properly, you must issue either a set output or set terminal command after the plot command.

The Push and Pop Pseudoterminals

The pseudoterminals terminal push and terminal pop can be very helpful in this context. The command set terminal push saves not only the current terminal type, but also all selected options. The command set terminal pop restores it. It’s therefore possible to restore the previous terminal state even without having explicit information about it.

Changing default terminal properties

A special command exists to change certain terminal options without having to reset the entire terminal. This can be useful when you want to modify some terminal aspect, regardless of the current choice of terminal. Five terminal properties can be changed using this command:

set termoption font "{str:name} [,{flt:size}]"
set termoption fontscale {flt:scale}
set termoption [no]enhanced

set termoption [ linewidth | lw ] {flt:factor}
set termoption [ dashlength | dl ] {flt:factor}

Be aware that only one aspect can be changed per invocation of set termoption; the different aspects can’t be combined into a single call.

Scaling a Complete Plot Up Or Down

It’s occasionally necessary to scale an entire, finished graph up or down—for a presentation, say, or for inclusion in a publication. Increasing the size of the resulting graph using set terminal ... size isn’t enough, because the line widths and font sizes won’t be scaled correspondingly. Instead, you want to adjust the fontscale and linewidth sub-options to the set terminal command as well.

The set termoption command may be helpful in this context, because it can adjust these two settings separately from the set terminal command. There is no equivalent terminal option for the size of symbols; you must use the set pointsize command for this purpose.

10.1.3. Terminal capabilities and the test command

Output devices (terminals) obviously can differ widely in their capabilities—you can’t get color plots from a black-and-white printer. Gnuplot has a built-in command called test that generates a standard test image. The test image shows all available line styles and fill patterns and also attempts to demonstrate more advanced terminal capabilities, such as the ability to rotate text through an arbitrary angle. To use the test command, you first need to select the terminal you’re interested in and set the name of the output file (if it’s not an interactive terminal) like so:

set terminal pdfcairo
set output "test.pdf"
test

Note that the command is test—not plot test!

In figure 10.1, you see the available line and symbol styles along the right side, fill patterns along the bottom, and line widths on the left. You can also see what kinds of arrows the terminal supports and whether it has the ability to rotate text. For the terminal as shown in the figure, all these features are supported.

Figure 10.1. The standard test image to demonstrate terminal capabilities, shown here for the pdfcairo terminal and the default color sequence set colorsequence default

Gnuplot terminals today

In recent versions of gnuplot, terminal handling has become easier and more consistent than ever. The improvements in terminals and terminal handling alone justify upgrading to gnuplot 5 at the earliest possible moment!

A huge advance is the development of a family of terminals that are all based on a common set of high-quality libraries for graphics and font handling. The pngcairo, pdfcairo, epscairo, and wxt terminals all use the cairo and pango libraries for graphics and font rendering, and the fontconfig facility for font selection. These libraries provide advanced capabilities, enabling gnuplot terminals to produce high-quality graphics output. Moreover, because an entire family of terminals shares a common back end, it’s now possible to generate bitmap (PNG), vector (PDF and EPS), and interactive (wxWidgets) versions of the same graph, with only minor differences between them.[a]

a

In particular, many of the configuration tricks and tweaks required by the bitmap terminals based on the GD library and the PostScript terminal are no longer necessary.

Even outside this family of terminals sharing a common back end, terminals in gnuplot 5 exhibit more consistent behavior than ever before. A common set of options is available for basically all contemporary terminals. Terminals are guaranteed to offer at least eight line types that have the same appearance (with regard to color, dash pattern, and point type) across all terminals. A background color can be selected as part of the set terminal command.

Font handling, in particular, has become much easier, because all contemporary terminals obtain their font support from the underlying font subsystem in the same way. Enhanced text mode (see section 10.2.3) is supported and is enabled by default. At the same time, some traditional uses of enhanced text mode are no longer as relevant: thanks to Unicode and UTF-8 encoding, special symbols can now be requested without an explicit font change, and the font subsystem will do its best to provide a suitable glyph.

By default, terminals produce colored graphs using solid lines. The option mono is still available for all terminals to enforce graphs in black and white, but it does not automatically turn on dashed lines, essentially rendering this option useless. (The options solid and dashed are still accepted by most terminals but are ignored.) You therefore have to select dash patterns explicitly (either globally using set linetype or inline with dashtype); thus you’re overall better off using a stylesheet (see section 12.6) to define a set of line types that have both the desired dash type and the required color when you want to create graphs in black and white.

10.2. Font selection and enhanced text mode

Fonts aren’t handled by gnuplot itself—instead, gnuplot relies on capabilities of the installed system libraries (and, of course, on the selection of installed fonts). In this section, we investigate how to tell gnuplot to use a specific font from among the available ones, and we introduce enhanced text mode, which allows additional formatting options for text.

10.2.1. Font selection

There are three ways to select a font, in increasing order of granularity:

  • Terminals have a default font that’s used for all text labels (unless overridden). You can select a different default font using the font keyword in the set terminal command.
  • Most commands that generate textual output (such as set label and set key) let you select a font explicitly, again using the font keyword. The font is used only for the specific label in question.
  • Using enhanced text mode, you can change the font inside a string. This makes it possible to render individual characters using a specific font if necessary or desired.

Another reason the default font is important is that the average size of its characters is used to define the character coordinate system (see section 7.2) and to set the size of the graph’s margins (see section 9.5.3). For variable-width fonts, gnuplot makes a best-effort attempt to determine an average character size.

10.2.2. Font resolution

In general, all terminals rely on some underlying system library for font resolution. Most contemporary terminals, and in particular the ones based on the cairo library, use the fontconfig utility for this purpose. One important service this library provides is font substitution: given a request for a font, it selects that font from among the available ones that most closely matches the request, taking into account not just the name of the requested font but also font characteristics such as style, slant, and weight. This “ensures that a font will always be returned, but doesn’t ensure that it is anything like the requested pattern,” as the fontconfig user manual says.[1] The details of the matching process, and in particular the relative priority of the various attributes, are complicated and not necessarily transparent to the user. The substitution occurs glyph by glyph: I’ve encountered instances where each character in a string of special characters was rendered using a different font, depending on which font in the list of candidates first provided a glyph for the requested character.

1

One particular problem concerns the rendering of mathematical symbols and Greek characters. In general, textual labels on a graph should support the graph but not distract from it. That calls for a clear and neutral font, like Helvetica or another linear sans-serif font with little line-width variation. In contrast, mathematical symbols and Greek letters are traditionally drawn with varying stroke weight. If a sans-serif font is selected as the default font for a terminal, then the font subsystem will attempt to find sans-serif glyphs for all requested characters, even for special symbols. To avoid this, I’ve found it necessary to switch fonts inside a string, particularly when I wanted to use letters from the Greek alphabet.

Figure 10.2 shows the results produced on my system when various free fonts are requested using the test script in listing 10.1. (Depending on what fonts you have installed, your results may differ.) The test string consists of a set of regular characters chosen to exhibit the particulars of the font and a selection of mathematical symbols. The first group of fonts consists of non-serifs, the second group of serif fonts, and the last group of three special math fonts. (OpenSymbol is distributed with Open-Office/LibreOffice, AsanaMath is intended as complement to Palatino, and the STIX project intends to provide a “comprehensive set of fonts” for scientific publishing.)

Figure 10.2. Output produced when various free fonts are requested on my computer—your version may look different. The first part of the test string contains a selection of characteristic regular characters, and the second part consists of common mathematical symbols and Greek letters.

Listing 10.1. Commands for figure 10.2 (file: font-demo.gp)
unset border; unset tics; unset key

set t pdfcairo size 14cm,17cm
set output "fonttest.pdf"

s = "Quarges Gyt R17"
t = "Σαλ∝ ∫Γ(θ . π) dφ → ∞"

f = "Helvetica 'Nimbus Sans L' FreeSans TexGyreHeros Arial "
f = f . "Verdana 'DejaVu Sans' 'Liberation Sans' 'Droid Sans' ? "
f = f . "Times Palatino 'Bitstream Charter' Utopia 'Century Schoolbook L' ? "
f = f . "OpenSymbol STIXGeneral 'Asana Math'"

a = 0; b=2.75; c=5.75
n = words(f); m = n

do for[k=1:n] {
  m = m - 1
  w = word(f,k)
  if( w ne '?' ) {
    set label w at a,m font "Helvetica,12"
    set label s at b,m font sprintf("%s,16", w)
    set label t at c,m font sprintf("%s,16", w)
  }
}
plot [-0.25:9.25][-1:n] -2

10.2.3. Enhanced text mode

All contemporary terminals support enhanced text mode, which allows additional formatting options. In enhanced text mode, some characters become control characters and indicate, for example, sub- and superscripts. As of gnuplot 5, enhanced text mode is now the default for all terminals. Enhanced text mode can be enabled or disabled for individual elements (such as text labels or the key) that contain strings. This may be useful if you want to use the special characters in regular text. Table 10.1 lists the special characters and their effects.

Table 10.1. Control characters for enhanced text mode

Control character

Example

Result

Description

{}     Establishes groups and scopes
^ x^2 X2 Superscript
_ A_{ij} Aij Subscript
@ x@^s_i Aligns sub- and superscripts vertically
  x@_i^{-3/2}y You need to put the shorter one first...
  x@^{-3/2}_iy ... rather than last.
{/ } {/Times Hello} Hello Changes the font
{/= } {/=24 A} A Selects an absolute font size (size in printer points)
{/* } {/*0.5 A} A Changes the font size relative to the enclosing font
{/:Normal } {/:Normal Hello} Hello Selects regular font characteristics
{/:Italic } {/:Italic Hello} Hello Selects italics
{/:Bold } {/:Bold Hello} Hello Selects boldface
& [&{abc}] [ ] Space, corresponding to the length of the enclosed argument
~ ~B/ Overlays the two following characters or groups
  ~x{.5-} Overlays a - character on the previous character, raised by 0.5 times the current character size
{ x ~ y } { x ~ y } Escapes a special character by preceding it with a backslash in single-quoted strings
\ \{ x \~ y \} { x ~ y } The backslash must be doubled to escape special characters in double-quoted strings.
NNN 101 A Selects a symbol using its octal code (single-byte characters only)
NNNNNN 316261 α Selects a multibyte character using a sequence of octal numbers, one for each byte in the binary encoding of the character. (The Unicode character α at code point U+03B1 has the binary representation 0xCE 0xB1 in UTF-8, which translates to 316261 in octal numbers.)

Here are some additional remarks on enhanced text mode:

  • Curly braces {...} are used both to group several characters together and to limit the effect of a font declaration to the contents of the braces only. They can be left off for single-character sub- and superscripts.
  • Phrases in curly braces nest, as in e^{-x^2} or a^{x_i}.
  • Font specifiers must be preceded by a slash / that immediately follows the opening curly brace.
  • Font specifiers can be combined into a single expression: for example, {/Times:Italic*2 Hello}.
  • Font specifiers apply to everything within the enclosing braces: {/:Italic a_k} creates a label where both characters are italic. To prevent the subscript from being italic, you must either take it outside the braces, as in {/:Italic a}_k, or use an explicit :Normal, like so: {/:Italic a_{/:Normal k}}.
  • A character within the single-byte ASCII range can be selected by supplying its ASCII code as a three-digit octal number preceded by a backslash.

  • Similarly, a multibyte Unicode character can be selected by encoding each byte of its binary representation as a three-digit octal number. Remember that the Unicode codepoint U+xxxx does not equal the binary representation in UTF-8. Instead, you have to look up the binary representation, convert each byte separately to a three-digit octal number, and then supply the sequence of numbers thus obtained.
  • Special characters can be used in enhanced text mode by preceding them with a backslash for single-quoted strings and by preceding them with a double backslash \ for double-quoted strings.
  • Overlays and the escaping of special characters aren’t available for the original postscript terminal. Both work normally for the pdfcairo and epscairo terminals.
Enhanced text mode vs. Unicode

Enhanced text mode used to be very important for two applications that today are better solved through Unicode. Overlays (using the ~ operator) were a way to create accented characters, and special characters (such as Greek letters and certain mathematical symbols) could be accessed by switching to a different font, like the PostScript Symbol font.

Today, both of these effects are better achieved through Unicode. Dedicated glyphs for accented characters almost always look better than an ad hoc solution using overlays; and system-wide font subsystems do their best to return a suitable glyph when a special symbol is requested, without you having to declare a specific font.

This leaves enhanced text mode as a solution for basic formatting tasks: sub- and superscripts, and local changes in font size and appearance (italics and boldface). Nevertheless, font changes are still available, and you’re free to use them if you have reason to override the selection made by the font subsystem.

10.2.4. Worked example

Let’s look at some examples of enhanced text mode (see listing 10.2 and figure 10.3). Most of the commands should be clear; I only want to point out a few details. Enhanced text mode can be used anywhere that gnuplot expects a string: in the example, it’s used in the labels, for the x tics, and for the entries in the graph’s key. The scope of a font selection can be limited using curly braces. This is done several times: for example, in expressions such as {/OpenSymbol φ}(x), which prints the first character using the OpenSymbol font but the last three using the regular font.

Figure 10.3. Enhanced text mode. See listing 10.2.

A word of warning: enhanced text mode works best for simple applications, such as sub- and superscripts, boldface and italics, and simple changes to the font size or font face. But complicated, nested expressions may not always work out perfectly (in particular when using the PostScript terminal—see the gnuplot standard reference documentation for details).

Listing 10.2. Commands for figure 10.3 (file: enhanced-mode.gp)
set label 1 "{/OpenSymbol f}(x) = e^{-x^2/2} / √2{/OpenSymbol π}" at 1.2,.25
set label 2
 "{/OpenSymbol F}(x) =  @_{-8}^x &{i} {/OpenSymbol f}(t) dt" at 1.2,0.8
set label 3 "{/:Bold*2 Big and Bold}" at -2.5,0.6

set key top left title "{/:Bold Legend}"

set xtics ( "{/OpenSymbol p}/2" pi/2, "0" 0, "-{/OpenSymbol p}/2" -pi/2 )

plot [-3:3] exp(-0.5*x**2)/sqrt(2*pi) t "{/OpenSymbol f}(x)",
         norm(x) t "{/OpenSymbol F}(x)"

10.3. Generating PNG and PDF with cairo-based terminals

The pngcairo and pdfcairo terminals are the first choice when it comes to generating graphs in a standard bitmap (PNG) or vector (PDF) file format. (There is also the epscairo format, which is equivalent to the pdfcairo format but produces encapsulated PostScript.) These terminals share a common set of options:

set terminal [ pngcairo | pdfcairo | epscairo ]
             [ size {flt:x}[ in|cm ],{flt,y}[ in|cm ] ]
             [ font "{str:face} [, {int:size}]" ] [ fontscale {flt:scale} ]

             [ background rgb {colorspec} ] [ [no]transparent ]
             [ [linewidth|lw] {flt:factor} ][ [dashlength|dl] {flt:factor} ]

             [ butt | square | rounded ]
             [ [no]enhanced ] [ [no]crop ] [ mono | color ]

The only option that requires some care is size, because it treats units differently depending on the output format:

  • For PNG, the size defaults to 640×480 pixels (aspect ratio 4:3). If no units are specified, pixels are assumed; if either cm or in is given, the size is converted to pixels, assuming 72 pixels per inch.
  • For PDF and EPS, the size defaults to 5×3 inches (aspect ratio 5:3). Other sizes can be specified using either cm or in as units; if no units are given explicitly, inches are assumed.

Most of the other options are straightforward:

  • You can choose a typeface and size for the terminal’s default font. The default is font "sans,12" (but see fontscale). You can give only the size, leaving the font blank: font ",16".
  • Using fontscale, you can adjust the size of the font separately and relative to the current font size. Be aware that the default value of this option is 0.5!
  • You can specify a background color using any one of the explicit color specifications (those using the rgb keyword—see section 9.1.1). Using transparent makes the background color transparent.
  • Line widths (for vector formats) default to 0.25 points (with 72 points per inch). Both the line width and the dash length can be changed by a multiplicative factor. Note that it’s not possible to change the point size in the same manner; you have to use the global set pointsize option instead.
  • The keywords butt, square, and rounded control how the cairo library renders line ends and joins (see figure 9.8). The default is butt.
  • Enhanced text mode is the default. You can disable it using noenhanced—for instance, because you want to use its control characters as regular characters.
  • When you use crop, the terminal attempts to trim empty space around the graph before saving it. The plot isn’t rescaled, so the resulting graph is in general smaller than the size specified in the size directive. (The crop option is only available for pngcairo.)
  • By default, terminals produce colored output. You can force monochrome output using mono, but be aware that this does not automatically turn on dashed lines—you have to do so explicitly for each line in your graph.

10.4. Using gnuplot with LaTeX

One very common use of gnuplot graphs is to include them as illustrations in a LaTeX document. This section presents a couple of cookbook-style recipes. First, I describe how to include a regular graphics file as an image in a LaTeX document.

Then we discuss gnuplot’s special cairolatex terminal, which allows you to combine gnuplot graphics with LaTeX text in the same illustration so that you can use the full power of LaTeX for mathematical typesetting in gnuplot graphs.

10.4.1. Including a graph in a LaTeX document

Including an external figure in LaTeX is fairly easy. One possibility is to use the graphicx package. This LaTeX package can handle both bitmap and vector formats, but for best results you want to use a vector format when available.[2]

2

Also keep in mind that you may have to use pdflatex when using graphics in PDF format, but plain latex for EPS graphics. Some newer TeX installations perform the necessary format conversion automatically.

As an example, let’s assume you want to include the graph from figure 10.3 in a LaTeX document. You’d have to export the graph to PDF, using the following commands:

The resulting file can then be included into a LaTeX document. The complete LaTeX document is shown in the following listing.

Listing 10.3. Importing a PDF into LaTeX: see figure 10.4 (file: doc1.tex)
documentclass{article}
usepackage{graphicx}

egin{document}

section{The First Section}

Here is a very short paragraph. The plot will be included
after this paragraph.

egin{figure}[h]
  egin{center}
    includegraphics[width=10cm]{enhanced}
  end{center}
  caption{A gnuplot graph, included in LaTeX}
end{figure}

And here is a second paragraph. The graph should have
been included before.

section{The Second Section}

The second section really contains only a very short text.
end{document}

The graphicx package provides the includegraphics command, which takes the name of the graphics file to include as a mandatory parameter. (The filename extension isn’t required, and it’s recommended that you omit it.) The include-graphics command takes a number of optional parameters as key/value pairs, which let you perform useful operations on the image as it’s included: you can trim, scale, and rotate it. Here, its size is adjusted ever so slightly (from 5 inches to 10 cm).[3] The document’s final appearance after processing with LaTeX is shown in figure 10.4.

3

There are many more options—check your favorite LaTeX reference for details. A good place to start is H. Kopka and P. W. Daly, Guide to LaTeX, 4th ed. (Addison-Wesley, 2004).

Figure 10.4. The final appearance of the LaTeX document shown in listing 10.3. Note the labels using enhanced text mode in the included gnuplot graph.

10.4.2. Using the cairolatex terminal

In the previous example, a graphics file containing enhanced-mode text was included in a LaTeX document. This seems inconvenient, to say the least: because LaTeX has such powerful capabilities to format text (and mathematical expressions specifically), there should be ways to use them to lay out the text, rather than dealing with the much more limited possibilities available through enhanced text mode.

The cairolatex terminal does exactly that: it splits a gnuplot graph into its graphical and textual components. The graph is stored as a PDF (or EPS) file, and the text is saved to a LaTeX file. You then include this LaTeX document, which in turn imports the graphics file, into your LaTeX master file.[4]

4

The cairolatex terminal is a modern replacement for the epslatex terminal, but epslatex remains available as well.

Tip

When gnuplot generates a file that has to be postprocessed using LaTeX, it’s particularly important to close the file properly by invoking set output after the plot is finished: otherwise, the generated file won’t be complete, and LaTeX will fail. (This applies equally to the cairolatex terminal, as well as to the tikz terminal later in this section, and other comparable terminals.)

A Worked Example

An example will make this clearer. Let’s re-create the graph from figure 10.4, this time using LaTeX formatting commands instead of enhanced text mode. See the next listing (compare to listing 10.2 for a version of this graph using enhanced text mode).

Listing 10.4. Combining gnuplot and LaTeX using cairolatex (file:cairolatex.gp)

The text for labels and tic marks that are added to the graph now contains LaTeX directives. In particular, note the $...$, which indicate math mode in LaTeX and which are required for many of the special mathematical formatting commands.

All the strings in listing 10.4 use single quotes, and therefore the backslashes they contain don’t need to be doubled. If you used double quotes instead, then all the contained backslashes would have to be escaped. The third label, for example, would have to be written like so:

set label 3 "\textbf{\Large Big and Bold}" at -2.5,0.6

The cairolatex terminal generates two files: the graph (as a PDF or an EPS file) and the text (as a LaTeX file). Gnuplot expects the full name (including extension) of the LaTeX file to be set using set output when you use the cairolatex terminal (see the third-to-last line in listing 10.4). The following listing shows the LaTeX master file.

Listing 10.5. LaTeX document that imports cairolatex.tex (file: doc2.tex)
documentclass{article}
usepackage{graphicx}

egin{document}

section{The First Section}

This is a different document. We will include a LaTeX file
containing the graph below.

egin{figure}[h]
  egin{center}
    input{cairolatex}
  end{center}
  caption{A graphics file included in LaTeX, with LaTeX labels}
end{figure}

And here is a second paragraph. The graph should have
been included before.

section{The Second Section}

The second section really contains only a very short text.

end{document}

Note how similar this document is to the one in listing 10.3. The graphicx package must again be specified explicitly. The document then uses input (instead of includegraphics—that’s the only difference) to include the LaTeX file written by gnuplot. Again, it’s recommended that you omit the extension: LaTeX will look for a file with .tex extension. The final document (after LaTeX processing) is shown in figure 10.5.

Figure 10.5. The final appearance of the LaTeX document shown in listing 10.5. Note the true LaTeX labels and tic marks on the graph. Compare to figure 10.4.

Options for the Cairolatex Terminal

Now that you’ve seen how the cairolatex terminal is used, we can take a closer look at its features. It shares most of its features with the pngcairo and pdfcairo terminals:

set terminal cairolatex [ eps | pdf ] [ standalone | input ]
             [ header "{str:header}" | noheader ]

             [ size {flt:x}[ in|cm ],{flt,y}[ in|cm ] ]
             [ font "{str:latexfont}[,{int:size}]" ][fontscale {flt:scale}]

             [ background rgb {colorspec} ] [ [no]transparent ]
             [ [linewidth|lw] {flt:factor} ][ [dashlength|dl] {flt:factor} ]

             [ butt | square | rounded ] [ [no]crop ]
             [ blacktext | colortext ] [ mono | color ]

Only three options are new: using the eps and pdf keywords, you choose the format of the graphics part of the output. Be aware that the default is eps (not pdf).

If you select standalone, the generated LaTeX document is complete and can be compiled by itself. In other words, it doesn’t have to be included into another LaTeX document for further processing. This way, you can create standalone graphics with LaTeX-style annotations.

In standalone mode, the name of the generated graphics (PDF or EPS) file is modified by appending -inc to the base name: the two files written by cairolatex would be called, for example, graph.tex and graph-inc.pdf. This means that the resulting graph, which combines both plot and text, can still be named graph.pdf. The default value for this option is input, which generates an incomplete LaTeX document for inclusion in a master file, as shown earlier.

The last new option is header. With it, you can add an arbitrary set of LaTeX commands into the LaTeX file containing the text component of the plot. For instance, you could use this

set terminal cairolatex header "\bfseries"

to print all text in the plot in boldface.

If LaTeX finds the file gnuplot.cfg when processing a standalone file, it’s included in the preamble of the document. It’s included before the argument to the header option, so the latter can be used to override global settings from the gnuplot.cfg file.

Finally, the font option changes its meaning for the cairolatex terminal, compared to the pdfcairo and pngcairo terminals. Instead of the names of system fonts, cairolatex obviously expects names for LaTeX fonts. The font description consists of three parts: the font name, the font series, and the font shape. All three parts are optional, but the commas are mandatory. Here are two quick examples:

You can give the size of the font after the font description: set terminal cairolatex "cmr" 14.

The cairolatex terminal provides additional ways you can access LaTeX features from within a gnuplot command script. Check the gnuplot standard reference documentation and your favorite LaTeX reference for more details.

10.4.3. Letting LaTeX generate the graph

When you use the cairolatex terminal, gnuplot draws the graph, and LaTeX provides the text labels. You can go a step further and let LaTeX draw both the text and the graph. Gnuplot merely creates a set of LaTeX commands that accomplish both tasks. Several terminals take this approach; here I’ll briefly introduce the tikz terminal as an example for the overall concept. The context terminal follows a similar idea.

The tikz terminal uses the Lua language to create the required LaTeX commands. The next listing re-creates the graph from listing 10.4 but uses the tikz terminal.

Listing 10.6. Commands for figure 10.6 (file: tikz-demo.gp)

Notice that the tikz terminal is invoked with the standalone option: in this case, you’re creating just the graph. Gnuplot produces a LaTeX file called tikz.tex that can be processed using pdflatex. Some auxiliary files that are required by LaTeX are part of the gnuplot distribution, but you can also generate local copies of them in the current directory by including the keyword createstyle in the call to set terminal tikz .... The resulting graph is shown in figure 10.6. Be aware that you need to have the pgf (TeX Portable Graphics Format) package installed, which is part of the LaTeX distribution but may not be installed by default.

Figure 10.6. A graph drawn using the tikz terminal. See listing 10.6 for the commands.

How does this entire approach compare to the alternatives? Historically, one advantage of letting LaTeX generate the graph was that LaTeX allowed greater control over the appearance of lines, dash patterns, and the like. This aspect has become less important as gnuplot has acquired some of these capabilities.

Terminals such as pdfcairo produce a separate (standalone) graph, which potentially has to be included into a document. Using the tikz or context terminal, you can embed the commands that generate the graph into the document, so only a single file has to be processed. Whether this is a good idea is another question—personally, I prefer the separation of concerns provided by having standalone graphs and a document that references them. Also be aware that LaTeX may encounter resource (specifically, memory) limitations when processing large graphs.

10.5. Scalable graphics for the Web with SVG and HTML5

Traditionally, graphics to be displayed in web pages were bitmaps—and you can still do this, using the pngcairo terminal, for instance. But gnuplot can also generate graphs using scalable formats that can be rendered in a web browser. The svg terminal creates a graph using the Scalable Vector Graphics (SVG) format; the canvas terminal prepares JavaScript commands for use with the HTML5 canvas element.

10.5.1. The svg terminal

The svg terminal behaves similarly to the pngcairo and pdfcairo terminals, but it creates SVG code, which can be captured in a file using set output:

set terminal svg [ size {int:x},{int:y} [ fixed | dynamic ] ]
                    [ font "{str:name} [, {int:size} ]" ]
                    [ fname "{str:fontname}" ] [ fsize {int:fontsize} ]
                    [ fontfile {str:filename} ] [ [no]enhanced ]

                    [ rounded | butt | square ] [ background rgb {colorspec} ]
                    [ [linewidth|lw] {flt:fac} ] [ [dashlength|dl] {flt:fac} ]

                    [[ mouse ] [ standalone | jsdir "str:dirname" ]]
                    [ name "{str:title}" ]

You can specify a size in pixels; the default size is 600×480. By default, or if the keyword fixed is given, the resulting graph has an absolute size; if dynamic is given, then the resulting graph adapts to the size of the viewer (typically filling the entire available area).

A font can be specified using the usual format, but you can also specify only a font name or font size using the keywords fname and fsize. Using fontfile, a file with font information can be embedded into the SVG document; gnuplot searches for the requested file using the information in the GNUPLOT_FONTPATH environment variable. The font must be an SVG font, not a PostScript or TrueType font.

The keyword mouse enables mousing: mouse coordinates are continuously displayed when the mouse is over the image; and individual curves can be toggled on or off by clicking their entry in the graph’s key. Mousing requires an external JavaScript script, which is usually found in a standard location of the local gnuplot installation; you can change the location by providing a path name to the jsdir option. The standalone option embeds the mousing code in the SVG file, rather than referring to an external document. Finally, you can use name to give the plot an identifier by which it can be referred to by JavaScript or a web page that includes the graph.

An SVG file can be used by itself or included in a web page. It’s recommended that you use the <object> tag for this purpose, like so:

<object type="image/svg+xml" data="graph.svg">
  Your browser does not support SVG.
</object>

This also provides a fallback message to the user, in case the user’s browser doesn’t support SVG.

10.5.2. The canvas terminal

The canvas terminal creates JavaScript commands that draw onto an HTML5 canvas element. It can be called in two different modes:

  • Using standalone, the terminal produces a web page (that is, HTML code) containing a <canvas> element and the JavaScript to draw on it. The set output option should therefore specify a file with extension .html (or equivalent).
  • The name option identifies the name of a JavaScript function that will be generated, and the terminal produces just the set of JavaScript commands that implement that function. The set output option should specify a file with extension .js.

The canvas terminal supports various options:

set terminal canvas [ size {int:x},{int:y} ]
                    [ font "{str:name} [,{int:size}] ] [ fsize {int:size} ]

                    [ [no]enhanced ]
                    [ title "{str:title}" ]
                    [ rounded | butt | square ] [background rgb {colorspec}]
                    [ [linewidth | lw] {flt:fac} ]
                    [ [dashlength | dl] {flt:fac} ]

                    [ standalone [mousing] | name "funcname" ]
                    [ jsdir "{str:url}" ]

You can specify a font using font. This setting is currently ignored, but a font size can be selected using fsize.

In standalone mode, the terminal creates a complete web page, which includes the JavaScript code for the graph. In addition, the web page refers to various other JavaScript files that are part of the gnuplot installation and that it expects to find in a standard location. You can specify a different directory using the jsdir option; this may be appropriate when the web page isn’t viewed locally, but is served on the Web. If the mousing keyword is used in conjunction with standalone, then some additional elements are included in the page that show the mouse coordinates and provide further ways to interact with the graph (such as zoom and unzoom functionality).

When the name option is used, gnuplot generates only the JavaScript. The resulting code contains the implementation of a JavaScript function with the desired name. For example, assume that you’ve created a JavaScript file called plotter.js, containing a function called drawplot(), using the following commands:

These files can be used in a web page like the one in the following listing.

Listing 10.7. Using the canvas name terminal (file: canvas-demo.html)
<html>
  <head>
    <script src="/usr/share/gnuplot/5.0/js/canvastext.js"></script>
    <script src="/usr/share/gnuplot/5.0/js/gnuplot_common.js"></script>
  </head>

  <body onload="drawplot();">
    <script src="plotter.js"></script>
    <canvas id="drawplot" width=600 height=400>
      <div id="err_msg">Your browser does not support HTML5 canvas.</div>
    </canvas>
  </body>
</html>

Several details are important:

  • The header section references two external scripts, which are part of the gnuplot distribution. Make sure the path to these files is correct in the header and that the files are visible.
  • The name of the function appears twice in the page: as the value of the onload attribute of the <body> tag, and as the value of the id attribute of the <canvas> tag.
  • The name of the generated JavaScript file is used in the <script> tag within the page’s body.

10.6. Interactive terminals

In contrast to the large range of options available for file-based terminals, interactive terminals are rather straightforward.

10.6.1. Common options

Gnuplot can have multiple plot windows open simultaneously, although only one of the windows will receive plot commands at any time. You can create a new plot window by specifying the terminal ID (which is just an integer expression) when choosing the terminal, like so:

set terminal wxt 1

To switch between open windows, use set terminal together with the terminal type followed by the window ID to select the active terminal. The keyword close in a set terminal command closes the identified window. (Depending on the window manager, the window may persist until it has received mouse or keyboard focus for the first time after the set terminal ... close command has been issued.)

To distinguish between multiple plot windows, you can give each one a title, which will (depending on the window manager) be displayed in the window’s header bar. (This is the title of the window only and has nothing to do with the title that can be placed on the plot using set title.)

Plot windows are automatically raised and receive input focus when a new plot is drawn. You can disable this behavior using the noraise option, so that keyboard focus stays with the command window even when a plot command is issued.

By default, pressing the space bar while the plot window has focus raises the command window, and pressing the Q key closes the plot window. Using the ctrl option, these bindings are replaced by combinations of the Ctrl key together with either the space bar or the Q key (thus freeing up those keys to be rebound otherwise: see section 12.4.3).[5]

5

Everything having to do with keyboard focus and the raising and lowering of windows depends on the interplay of the window manager and the widget set implementing the terminal. As of this writing, not all of this functionality works with all window managers.

When the persist option has been enabled, plot windows stay up even when gnuplot is exited (or prevent gnuplot from terminating completely until all plot windows have been closed explicitly).

You can use three commands to manipulate interactive terminals directly: raise, lower, and clear. The first two take an optional window identifier as optional argument. The clear command (which always acts on the most currently active terminal) is useful even for non-interactive terminals: it clears the plot area (and forces a form-feed or page break for non-interactive terminals). It’s required, for example, in some applications of multiplot mode (see section E.1).

10.6.2. The wxt and qt terminals

The wxt and qt terminals are very similar in their functionality but are built using different widget sets. Because both widget sets are cross-platform, both terminals are available on all current operating systems: Linux, Windows, and Mac OS X.

Both terminals share the most important options:

set term [ wxt | qt ] [ {int:id} ] [ title "{str:title}" ]
         [ size {int:width},{int:height} ] [ position {int:x},{int:y} ]
         [ font "str:face[,{int:size}]" ] [ [no]enhanced ]
         [ [no]raise ] [ [no]persist ] [ [no]ctrl ]
         [ close ]

In addition, both terminals support the dashlength (or dl) option. The wxt terminal (but not the qt terminal) also offers the background (or backg) and linewidth (or lw) options.

10.6.3. The aqua terminal

The aqua terminal is a native Mac OS X terminal for gnuplot. It relies on AquaTerm.app:

set term aqua [ {int:id} ] [ title "{str:title}" ]
              [ size {int:width},{int:height} ]
              [ font "str:face[,{int:size}]" ] [ [no]enhanced ]

10.6.4. The windows terminal

The windows terminal is for use on Microsoft Windows platforms:

set term windows [ {int:id} ] [ title "{str:title}" ]
         [ size {int:width},{int:height} ] [ position {int:x},{int:y} ]
         [ font "str:face[,{int:size}]" ] [ [no]enhanced ]
         [ close ]

The windows terminal supports some additional GUI features; see the standard gnuplot reference documentation for details.

10.7. Other terminals

As mentioned in the introduction to this chapter, gnuplot supports a lot of terminals—many more than I discussed in this chapter. Although most of them are no longer relevant, some may be of use in specialized situations.

Traditionally, the postscript terminal was very important, and so were the gif, png, and jpeg bitmap terminals based on the GD library. These terminals have largely been replaced by the pdfcairo and pngcairo terminals discussed earlier in this chapter.[6]

6

The default appearance of graphs produced using pdfcairo differs somewhat from those generated with postscript. Explicitly specifying the aspect ratio with set terminal pdfcairo size 5in,3.5in and adjusting the border thickness and point size with set border lw 1.5 and set pointsize 0.75 bring the results from the pdfcairo terminal much closer to the look familiar from the postscript terminal. If you want to create monochrome graphs, you’ll need to define your own dash patterns—see the stylesheet in listing 12.9 for an example. You may also want to specify the Helvetica font, but the result will depend on the selection of fonts installed on your system (whereas PostScript graphs were guaranteed to use the actual Helvetica, because it’s one of the 35 PostScript core fonts).

There are many more terminals that generate commands suitable for TeX or LaTeX processing than I described here. If you’re interested, you may want to check out the standard gnuplot reference documentation for eepic, latex, pslatex, pstricks, texdraw, and tpic.

In addition to LaTeX, gnuplot supports some other graphical command languages. Check out the fig and tgif terminals.

You should also know about two terminals that are truly obsolete but are still supported and may provide a safe fallback solution if necessary: x11 and dumb. The x11 terminal is built on the X11 system without the benefit of a modern widget system. As an X11 application, it honors many of the standard X11 conventions, such as geometry, color resources, and app-defaults. The x11 terminal has been superseded by terminals such as wxt and qt that are built using contemporary widget sets.

Finally, a true classic: the dumb terminal (see figure 10.7). This is a terminal for character-oriented output devices. It uses characters to draw an ASCII-art rendition of the plot: it’s the fallback for console-oriented systems or over really slow network connections. For all of these terminals, see the standard gnuplot reference documentation.

Figure 10.7. The dumb terminal

10.8. Summary

Gnuplot uses the terminal facility to create output for other applications and devices. The pngcairo and pdfcairo terminals create graphs in standard bitmap (PNG) and vector (PDF) formats. The svg and canvas terminals can generate vector graphics suitable for inclusion in dynamic web pages.

The appearance of strings and text labels depends on the available fonts and the capabilities of the chosen output format. Enhanced text mode lets you embed simple formatting commands (such as sub- and superscripts) in text labels.

For those who are familiar with LaTeX, the cairolatex terminal makes it possible to use LaTeX’s text (and, in particular, math) formatting capabilities together with gnuplot’s plotting facilities to achieve particularly high-quality plots for publications or other printable documents. Finally, I provided a brief overview of interactive terminals for various platforms.

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

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