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.
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.
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.
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 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.)
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.
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!
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 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.
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.
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.
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.
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]
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.
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.
There are three ways to select a font, in increasing order of granularity:
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.
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.
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.)
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
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.
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:
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.
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.
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).
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)"
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:
Most of the other options are straightforward:
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.
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]
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.
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.
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).
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]
The cairolatex terminal is a modern replacement for the epslatex terminal, but epslatex remains available as well.
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.)
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).
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.
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.
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.
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.
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.
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.
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.
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.
The canvas terminal creates JavaScript commands that draw onto an HTML5 canvas element. It can be called in two different modes:
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.
<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:
In contrast to the large range of options available for file-based terminals, interactive terminals are rather straightforward.
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]
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).
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.
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 ]
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.
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]
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.
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.
18.225.254.192