**50%**off this eBook here

### gnuplot Cookbook — Save 50%

Over 80 recipes to visually explore the full range of features of the world's preeminent open source graphing system with this book and ebook

This article, written by Lee Philips the author of gnuplot Cookbook contains the following :

- Making a surface plot
- Using coordinate mappings
- Coloring the surface
- Making a contour plot
- Making a vector plot
- Making an image plot or heat map
- Combining contours and images
- Combining surfaces with images
- Plotting a path in 3D
- Drawing parametric surfaces

# Making a surface plot

A surface plot represents the dependent quantity z, which depends on the two independent variables x and y, as a surface whose height indicates the value of z.

The previous figure is a perspective drawing of a surface representing the Bessel function J0(r), where r is the distance from (x=0, y=0). The height of the surface shows the value of J0, given on the vertical axis (unlabeled in this figure, but usually called z). The other two (unlabeled) axes defning the plane above which the surface is drawn are the x and y axes.

## How to do it…

The following code listing is the script that coaxed gnuplot into making the previous figure:

set isosamples 40

unset key

set title "J_0(r^2)"

set xrange [-4:4]

set yrange [-4:4]

set ztics 1

splot besj0(x**2+y**2)

set view 29,53 #Done implicitly by mousing.

set term pngcairo mono enhanced

set out 'bessel.png'

replot

## How it works…

There are several new commands in this recipe. The set isosamples command sets the **isoline density**. This is analogous to the set samples command when making 2D plots, but it sets the number of lines used in forming the surface. The number of isosamples can be set independently in each direction; if one number is specifed, it is used for both directions. The default of 10 usually creates surfaces that are far too coarse to be useful.

Turning to the second of the highlighted commands, the splot command is the 3D version of our old friend the plot command (it probably initially stood for "surface plot", but now can do several things besides plot surfaces, as we shall see in the rest of this article). It expects a function of x and y rather than x alone. Although we are interested in plotting something that has the type of symmetry that would be most conveniently expressed in polar (spherical or cylindrical) coordinates, these geometries are not available for function plots in 3D in gnuplot. (They are available through the set mapping command for data plots, as we shall see later in this article.) Therefore in such cases, we are required to convert our expressions to the rectangular coordinate system. Instead of what we would call r in a cylindrical coordinate system, here we use the equivalent x**2 + y**2.

In this recipe, we would like to illustrate, as far as possible, the interactive approach to creating a fnal 3D plot. The next highlighted line, beginning with set view, can be entered on the command line or included in a script. The view is the orientation in degrees of the perspective drawing of the 3D plot. Naturally, it does arise in 2D. It is diffcult to determine what is the most useful view for a particular plot without looking at it and experimenting with it; therefore, even if our fnal product is intended to be a fle, a common workfow is to frst create the plot using an interactive terminal (x11 or wxt). Then we rotate the plot with the mouse, and possibly scale and zoom it using the middle mouse button, until we arrive at the desired appearance. This is what we mean by the comment in the set view command. Now we can reset the terminal to the fnal output device that we need, specify the output fle, and simply say replot. The view and scaling at which we left the interactive plot is retained as a set of global settings and will be refected in our fnal output fle. These settings are also displayed at the bottom of the interactive plot window, so we can record them if we are going to make similar plots in the future, or want a set of plots to be drawn with the same settings. Note that we also redefned the ztics value. This is because when the plot is tilted to the fnal view angle that we chose, the perspective causes the tic labels on the vertical axis to be crowded together; this is a common problem with 3D plots, and taking manual control of the tics on the z-axis is the solution.

## There's more…

Following is the same plot with one setting changed (aside from a slight adjustment in the view angle):

While the frst plot was essentially a wireframe that we could see through, this version has the appearance of a solid, opaque surface. All we need to do is to say set hidden3d. This, which only works when lines or linespoints are being used, makes the surface appear opaque by removing from the plot any part of the surface, other surfaces, and other plot elements such as the axes and tic labels, that are behind the surface from our point of view. The underside of the surface is shown in a contrasting color with a color output device, but the two sides of the surface are not distinguished in monochrome. The name of the setting refers to the technique of **hidden line removal**; gnuplot is justly famed for the quality of its hidden line removal algorithm, and is one reason this program is so well regarded for its 3D plotting ability.

# Using coordinate mappings

It is possible, when making 3D plots from data fles, for the data to be interpreted in spherical or cylindrical coordinates rather than the default Cartesian system. For details, type help set mapping. We will give an example of using the cylindrical mapping to conveniently draw a shape with cylindrical symmetry.

The previous figure is a perspective view of a surface that somewhat resembles a Christmas tree ornament. The relevant feature of this surface is that it has rotational symmetry around the z (vertical) axis, which means that it is most naturally expressed in cylindrical coordinates.

## How to do it…

Try the following script:

set mapping cylindrical

unset tics

unset border

set hidden

set xrange [-pi : pi]

set yrange [-pi : pi]

set zrange [0 : pi]

set iso 60

unset key

splot '++' using 1:2:(sin($2)) with lines

## How it works…

There are several new ideas used in this recipe. Breaking it down, these are:

### The set mapping command

The frst, highlighted line contains the new command that is the subject of this recipe. When the default Cartesian (x-y-z) coordinate system is changed to cylindrical then the columns of data read in during a data plot are interpreted as θ-z-r, where θ is the angular coordinate, z is the vertical coordinate, and r is the radius. A spherical mapping is also available and explained in the gnuplot online help (help set mapping). If the data fle only has two columns, then the plot is drawn with r = 1.

In our example we don't want to plot from a data fle, however. We want to plot a function given directly in the script. This presents us with a problem, as gnuplot does not support cylindrical or spherical plots of functions in 3D. The solution is to use one of gnuplot's **pseudofles**.

### The ++ pseudofle

The "++" pseudofle creates rows of imaginary data with three columns x-y-z unless we change the coordinate mapping, which of course in this example we have. Setting the mapping to cylindrical means that the fctitious data columns will be interpreted as θ-z-r.

Now to plot a function, we use the using notation applied to the imaginary columns of data. We've done this in the fnal line of the script, where we plot the sine of the second column (z).

To clarify the use of "++" when plotting surfaces, note that, in Cartesian coordinates, the two commands "splot sin(x)+cos(y)" and "splot '++' using 1:2:(sin($1)+cos($2)) with lines" produce exactly the same plot.

## Coordinate ranges

We have also established ranges for all variables in the set xrange and two other commands following it. The ranges for the polar coordinates are taken from the corresponding Cartesian coordinates, that is, when we set the xrange, we are setting both the range of the x-axis displayed on the plot and the range of the variable θ in the cylindrical coordinate system. It is mandatory to set xrange and yrange when using the "++" flename.

This mixing of the coordinate system in which the function is calculated and the Cartesian system in which it is displayed can be confusing, but the example shows a strategy, which should make it possible to get predictable results. Setting the xrange and yrange as we've done puts the r = 0 point in the middle of the graph and prevents part of the plot from being cut off. It also sets up a full rotation of the angular coordinate over a range of 2 p.

If we wanted to plot, say, our shape with half of it sliced off by a vertical plane, the easiest way to do this is not to fddle with the coordinate ranges, but to apply a transformation to one of the fctitious data columns: splot '++' using ($1/2):2:(sin($2)) with lines, will do the trick without any surprising side effects. In this example the underlying angular coordinate (column 1) still passes through a full rotation, but we've divided it in half without changing the way the figure is projected onto the Cartesian display. Note that the 60 isolines will still be used in our reduced angular range, so we might want to set iso to a smaller value.

### Completing the picture

We've eliminated all of the graph adornments (unset tics, unset border, unset key) so we will be left with only the surface. The isosamples are set to give a suffciently smooth surface drawing that is nevertheless not too crowded with isosurface lines (see the previous recipe). set hidden ensures that we shall see only the outer surface of the shape.

# Coloring the surface

The wireframe splot with hidden line removal that we covered in the frst recipe of this article, Making a surface plot, gives the visual impression of a solid surface. The numerical value encoded into the surface's height can be visually estimated, roughly, by the perspective provided by the isolines in conjunction with the tics on the vertical axis. But gnuplot also has a way to draw real solid surfaces whose height is indicated by color or shade.

The previous figure shows the same mathematical function plotted in the frst recipe in this article (Making a surface plot). Now the numerical value of the function at any point is indicated by both the height of the surface and its shade; the surface is now drawn as an opaque membrane rather than as a network of curves.

## How to do it…

To produce the previous figure, run the following in gnuplot:

set isosamples 100

set samples 100

unset key

set title "J_0(r^2)"

set xrange [-4:4]

set yrange [-4:4]

set ztics 1

unset surface

set pm3d

splot besj0(x**2+y**2)

The surface will be drawn with a palette of colors when a color output device is being used and with a grayscale palette when using a monochrome terminal.

## How it works…

If you compare the previous script with the one in the Making a surface plot recipe at the beginning of this article, you will see that the only signifcant difference is the highlighted line. The pm3d mode colors the imaginary surface being plotted according to its height or z-value at every point, with the mapping between the height and the color or shade determined by the **palette**, which we shall discuss in some more detail shortly.

The other modifcations are to increase the number of isolines, in order to get a smoother surface, and to turn off the drawing of the individual isolines themselves with the command unset surface. We also need to set the sample frequency; generally we want this to be equal to the isosample frequency. In pm3d mode, the two orthogonal sets of isolines are drawn with two different spacings given by the two parameters. Although the gnuplot manual claims that the global hidden3d setting does not affect pm3d surface plots, it in fact seems to, and should not be turned on, as it appears to slightly degrade the drawing quality.

## There's more…

Sometimes we want both a colored surface and a set of isolines; in fact, this can often be the clearest type of quantitative 3D plot. The way to achieve the highest quality in this type of graph is to use the hidden3d linestyle option to pm3d, as we do in the following script:

set iso 30

set samp 30

unset key

set title "J_0(r^2)"

set xrange [-4:4]

set yrange [-4:4]

set ztics 1

unset surf

set style line 1 lt 4 lw .5

set pm3d at s hidden3d 1

splot besj0(x**2+y**2)

This requires us to defne a user linestyle. Then the linestyle is referred to in an option to the set pm3d command. This will cause the isolines to be drawn using lines in this style, which allows us to have them in any color, thickness, or pattern supported by our terminal. Further, the isolines will be drawn with hidden line removal, so they will appear to be embedded in the opaque surface. As before, the global hidden3d option should not be turned on.

Note that we've also reduced the sample and isoline frequency, to keep our plot from being too crowded with isolines. (The at s component of the set pm3d command means at surface.)

Over 80 recipes to visually explore the full range of features of the world's preeminent open source graphing system with this book and ebook |

# Making a contour plot

A **contour** plot is a set of **isolines**, or curves where the function or data has a constant value, drawn in the plane of the independent variables (x and y in Cartesian coordinates). It is simpler than the surface plots covered in the previous recipes in that it doesn't require the interpretation of perspective or hidden line removal. As there is no z axis for reference, the value that each isoline represents is represented by an individual label or by giving each line its own dash pattern or color.

Certain types of patterns are better represented as surfaces, while for others, contours bring out more of the relevant characteristics. The rotationally invariant function that we plotted in the previous recipes in this article would yield a set of uninteresting circular contours; its structure is better conveyed by a surface plot. Here, we've plotted a function whose contour plot shows a pattern of nodal lines.

## How to do it…

The following code sample will get you a contour plot:

set cntrparam levels 10

set contour base

unset sur

set view map

set xrange [-4:4]

set yrange [-4:4]

set iso 100

set samp 100

set key rmargin

splot sin(x)+cos(2*y)

## How it works…

The number of contour lines drawn and which levels they follow are set with the set cntrparam command. The frst command in the script asks for 10 automatically spaced levels; the number of levels we specify will actually be used by the program as an estimate of the number of levels it should actually use, not an exact number. We can also specify exactly which contour levels to use, rather than letting gnuplot calculate a set of automatic levels; see the online help for an exhaustive description of your options.

The second highlighted command tells gnuplot that our next splot command should draw a contour plot, and that the contour lines should be drawn on the base of the axis system, which is the x-y plane. As we want a contour plot only, without a surface plot as well, we need to say unset sur[face], because the default behavior of the splot command is to draw a surface, as in the previous recipes.

The set view map command is a special option to the set view command that we saw previously. It rotates the coordinate system so that we are looking straight down from above, and is generally what we want for basic contour or image plots that shouldn't also incorporate surfaces.

As before, we need to set both the isosamples and the samples to get the desired number of contour lines in each direction. We place the legend, which will contain a key mapping each contour level to a color or dash pattern, on the right margin.

*While many output terminals will produce a nice colored contour plot, if you need to create a monochrome plot using dash patterns to distinguish the contour levels, as shown in the paper version of this book, then you need to use the postscript terminal. The output fle can then be easily converted to PNG or any other desired graphics format. But the other terminals, such as pngcairo, generally are not capable of producing high-quality (or any) dashed contours directly.*

## There's more…

Although we should be cautious about putting too much information on a plot, lest our graph become an indecipherable jumble of lines and curves, it is possible, with care, to combine contour and surface grid plots to produce a reasonable illustration such as the following:

This is a plot of the same function as shown previously, with a contour plot on the base, a surface, and another set of contours drawn on the surface. Here is the script:

set iso 50

set samp 50

set yrange [-4:4]

set xrange [-4:4]

set ztics 1

unset key

set style line 1 linecolor rgb '#cccccc'

set contour both

set cntrparam levels 10

set hidd

splot sin(x)+cos(2*y) with lines linestyle 1

We've defned a line style having a light gray color and used it in the splot command. This is so that the grid lines forming the surface will be easily distinguishable from the contour lines. The latter will be drawn in various colors or, as shown, where a monochrome output terminal was used, as dark lines. The view angle was adjusted interactively for this plot.

# Making a vector plot

When the quantity that depends on x and y has both magnitude and a direction it can be represented by an arrow whose length is proportional to the magnitude. The x-y plane can be broken into a regular grid and an arrow drawn in the plane, representing the direction and magnitude associated with each point on the grid—a **vector plot**. As we are associating two quantities, the magnitude and direction, or, equivalently, Δx and Δy, for each x-y pair, we can think of this type of plot as a 4D plot.

The previous figure is a vector feld of a rotating fow. The exact appearance of the arrows will vary with the output terminal.

## How to do it…

The following script draws the vector plot in the previous figure:

set xrange [0:pi]

set yrange [0:pi]

set iso 20

set samp 20

unset key

a = .2

plot '++' using 1:2:(-a*sin($1)*cos($2)):(a*cos($1)*sin($2))\

w vec size .06, 15 filled

## How it works…

Vector plots require a data fle or equivalent pseudofle. Four columns are used for x, y, Δx, and Δy. Our plot command uses a variable that we defned in the line above it, defnes the four columns using gnuplot's using math syntax for manipulating column data and, in the highlighted section, asks for a vector plot. The size specifcation sets the arrowstyle. The frst number is the length of the arrowhead and the second is the angle of the sides of the arrowhead in degrees. filled means to draw solid arrowheads. For all the details of how you can specify exactly how you want your vector arrows to look, say help arrowstyle at the gnuplot interactive prompt.

## There's more…

gnuplot has the ability to plot a vector feld on a surface, similarly to how it can plot contours on a surface, as we saw in the previous section.

The vectors are plotted on an imaginary surface that is not depicted explicitly. Experimentation shows that the arrowstyle cannot be changed by the user, despite the documentation, but depends only on the terminal. This type of plot can be used, for instance, to describe a fuid fow in 3D; the contrived example shown was chosen to make the script easy to understand:

set xrange [-pi:pi]

set yrange [-pi:pi]

set zrange [-pi:pi]

unset key

set iso 20

set samp 20

set ztics 1.5

set view 37,300

a = .9

splot '++' using 1:2:(2*a*cos($2)*sin($1)):\

(-a*sin($1)*cos($2)):(a*cos($1)*sin($2)):(a*cos($1)) w vec

The difference is the use of the splot command to create the vector plot rather than the plot command used previously for the planar vector plot. This requires six columns of data (or pseudo data): x, y, z, deltax, deltay, and deltaz.

# Making an image plot or heat map

The information that is presented in a planar contour plot can also be conveyed by coloring or shading the x-y plane, rather than by drawing contours on it. The resulting graph is called an **image plot**, or sometimes, a **heat map**:

Depending on the character of the data to be plotted and the features one wants to call attention to, and to some extent the physical characteristics of the output device, either a contour plot or an image plot might be preferred.

## How to do it…

The previous figure was created using the following script:

set xrange [-4:4]

set yrange [-4:4]

set iso 100

set samp 100

unset key

unset sur

set view map

set pm3d at b

splot sin(y**2+x**2) - cos(x**2)

## How it works…

Let's look at the highlighted code line frst. This set pm3d line, which we used at the beginning of the article to plot surfaces, here has the additional clause at b, which means at bottom. This says to draw the data color map on the x-y plane rather than on the surface itself. The line above it, which we also used before when learning how to make a contour plot, sets the view so that we are facing the x-y plane. With these preparations, the splot command creates an image plot using the default color palette. This palette is what defnes the mapping from data value to color (or to gray value for monochrome terminals, as in the figure prepared for the printed version of this book). Note also that we've bumped up the isoline and sample frequency (we must do both again, one for each direction) for a smooth image plot. The line unset sur[face] is required to tell splot not to draw the surface itself, which would put a distracting grid of lines on top of our image plot.

## There's more…

If we are using a color output device we may want to use something other than the default rainbow palette. gnuplot provides several different mechanisms for setting the palette, providing enough fexibility to specify any mapping we might require.

If we decide not to display the palette scale, the legend that shows the mapping from data values to colors, we need to use the following command:

unset colorbox

gnuplot allows us to read color tables from fles or to defne them with arbitrary mathematical functions that map from data value to each of the components of several available color spaces (RGB, and so on). There is even a library of predefned mathematical functions to choose from. But all this is fairly arcane and, in practice, we almost always want a linear interpolation between two or three specifed colors in order to defne a simple spectrum. Fortunately, gnuplot makes it very easy to do this. A few examples should make the method clear:

To get a spectrum that goes from black to gold, just give the command:

set palette defined (0 'black', 1 'gold')

The colors themselves can be specifed using named colors, as we did here (try typing show colornames at the interactive prompt to see the list of over 100 names and their RGB values) or with the familiar #RRGGBB syntax, or in any other gnuplot-approved way.

If we decide we would like another color in the middle of the spectrum, we can try:

set palette defined (0 'black', 1 'aquamarine', 2 'gold')

Note that the actual numbers are not important; gnuplot rescales them to the interval [0,1] and interpolates between them, where 0 would be black and 1 would be white if we were plotting in grayscale.

Sometimes we want a sharp break somewhere in the palette to highlight a particular data value; this has the effect of combining a contour with the image map. To do this, we repeat a value:

set palette defined (0 'black', 1 'aquamarine', 1 'red', 2 'gold')

This will create a sharp transition in the palette between aquamarine and red, exactly in the middle of the range. The lower half of the palette will be a smooth transition from black to aquamarine, and the upper half will go smoothly from red to gold. We can defne any number of these transitions, and create palettes of limitless complexity with this syntax.

Two more notes on mapping data to colors: If the data is better visualized with a logarithmic mapping rather than the default linear one, enter the set logscale cb command. To change the limits of the mapping, analogous to setting the z range, do set cbrange [a : b].

## Combining contours and images

Sometimes we would like to plot two related but different sets of data on the same graph. In the case of 2D plots, it's simple: we just plot any number of curves and identify them with labels or a legend. But with 3D plots, trying to interpret a graph containing two different surfaces or sets of contours would be diffcult, and plotting two heat maps simultaneously would not make any sense.

The previous figure shows one way to do this: plot contours and an image map together.

## How to do it…

Feed this code to gnuplot to get the previous figure:

set xrange [0:pi]

set yrange [0:pi]

set iso 100

set samp 100

set cntrparam levels 10

unset key

unset surface

set view map

set contour base

set pm3d at b

splot '++' using 1:2:($1**2-$2**2):(sin($1**2+$2**2))\

with lines lw 2

## How it works…

We set everything up as in the previous contour plot example, but we also put in a set pm3d at base, so we are asking for both a contour plot and a colored surface plot. How do we make the surface, which will appear as an image plot here, and the contours to represent distinct sets of data? The splot command, when plotting data from a fle or the "++" pseudofle, can take an optional fourth column. When this is present, it will be used to color the surface, which itself, as before, will be defned by the third column. This can be used to draw a surface in 3D perspective view, which is colored to represent some related quantity, rather than to redundantly indicate its height. Or, as here, it can be used to draw contours over a "surface" that is rendered as an image map. The function for the contours is given in the third column, which, using coordinate variables rather than the columns' index's, is x**2 - y**2, and the fourth column defnes the image map: sin(x**2 + y**2).

Over 80 recipes to visually explore the full range of features of the world's preeminent open source graphing system with this book and ebook |

# Combining surfaces with images

It is possible to plot a surface and its projection as a color image on the x-y plane on the same graph. The two simultaneous views of the same data or function can be useful to bring out the topography of a complex surface.

The previous figure shows a simple trigonometric function of two variables displayed as a surface with its values simultaneously encoded into colors (or gray values) at the base of the plot.

## How to do it…

The following script produces the previous figure as its output:

set iso 40

set samp 40

unset key

set xrange [-pi:pi]

set yrange [-pi:pi]

f(x,y) = sin(x)*cos(y)

set hidden front

set xyplane at -1

splot f(x,y) with pm3d at b, f(x,y) with lines

## How it works…

The new features we are combining to produce this graph are in the highlighted lines in the code sample. Let's look at the last command frst. The frst part of the splot command plots the function f(), which is defned three lines above, as a colored surface at the base of the plot; this is what pm3d at b does. The second part, after the comma, plots the function again, without pm3d but with lines. This plots the wireframe surface.

The function varies from -1 to 1, but we want it to lie completely above the base upon which the surface is drawn, so we need to change the z value at which we place the base. This is the purpose of the second to last line.

Finally, we would like the surface to appear solid. But when combining surfaces with pm3d color plots, we need to add an extra option to the set hidden3d command, because the hidden line removal does not apply to the pm3d part of the graph. The command set hidden front tells gnuplot to draw the parts of the graph involving the hidden line removal procedure after the other parts, so they appear to be "in front" of the colored base, giving the effect we want.

## There's more…

We can make the image intersect the surface, as shown in the following:

This is a simple 2D Gaussian surface cut through by the x-y plane, upon which the function's values are shown as colors or in grayscale. The code follows:

set samp 40

set iso 40

set yrange [-1.5:1.5]

set xrange [-1.5:1.5]

unset ytics

unset xtics

unset key

unset colorbox

set hidden3d front

a = .5

set xyplane at a

f(x,y) = exp(-x**2-y**2)

splot f(x,y) with pm3d at b, f(x,y) with lines, a with lines lt -100

We've taken advantage of the fact that we can place the base wherever we want to make it intersect the surface at a, which we've set to 0.5. But it's not quite so simple, as a little trick is required to make the color projection on the base to appear to be opaque; otherwise, we would be able to see the surface through it, which would make the graph confusing. Remember that hidden line removal does not work on the pm3d surface, so we need to add something else to the x-y plane to make it appear to be opaque. This is the purpose of the last part of the splot command, where we have asked for a plot of the constant value a using the linetype (lt) -100. As the global hidden3d option is turned on, this plot will be made using hidden line removal; and as we have specifed a linetype that happens not to exist, the lines themselves will be invisible. The net result is a surface, invisible except for its ability to hide what is beneath it, having the constant value a, which will exactly coincide with the base of the plot.

We can also plot two different sets of data or functions, one used for the surface and the other for the image:

The previous plot retains the 2D Gaussian surface from before but plots a simple 2D trigonometric function in an image. For good measure, we've thrown in a contour plot as well. The plot was made with the following script:

set samp 40

set iso 40

set yrange [-1.5:1.5]

set xrange [-1.5:1.5]

unset ytics

unset xtics

unset key

unset colorbox

set hidden3d front

a = .5

set xyplane at a

f(x,y) = exp(-x**2-y**2)

splot f(x,y) with pm3d at b, f(x,y) with lines, a with lines lt -100

set hidden3d front

a = .5

set xyplane at a

set contour base

f(x,y) = exp(-x**2-y**2)

splot '++' using 1:2:(a):(sin($1)*cos($2)) with pm3d at b,\

'++' using 1:2:(f($1,$2)) with lines, a with lines lt -100

By now, this should all be familiar, except for the last command. We've combined our previous tricks with the use of the "++" pseudofle in order to get different data used for the surface (and contours) and the image. This is the technique used earlier in this article in the Combining contours and images recipe.

## Plotting a path in 3D

We can use parametric plotting to make graphs of complicated 2D paths in 3D to draw a complex curve in space.

This might be thought of as a 3D Lissajous figure. The path intersects itself at several places.

## How to do it…

Following is the code for the previous figure:

set samp 100

set xtics .4

set ytics .4

set parametric

set urange [-pi:pi]

set ztics 1

splot cos(u),sin(3*u),cos(5*u) lw 2

Note that the appearance of the plot will change radically depending on the viewpoint.

## How it works…

In exploring parametric plotting in 2D, the x and y independent variables are replaced by the single parameter t, and we have to specify two functions separated by commas; the first gives the x coordinate and the second gave the y coordinate that were plotted simultaneously as t was varied between the limits defned in the trange.

To plot a parametric curve in 3D, it may not come as a surprise that we need to specify three functions (or data columns) separated by commas. This can be seen in the last command of the previous script. When we give the command set parametric in 3D, two new independent variables u and v are established, which act as the parameters. We need to set their ranges, which we do here with the set urange command (we don't use v in this example, but we do in the next, when we explore parametric surfaces).

# Drawing parametric surfaces

gnuplot allows us to defne surfaces parametrically, which allows us to plot complex and possibly self-intersecting shapes.

The previous figure shows a surface that slices through itself in 3D.

## How to do it…

Following is the script for the previous figure:

set param

set iso 50

set ztics .5

set xtics .4

set ytics .4

set urange [-pi:pi]

set vrange [-pi:pi]

set hidd

splot cos(u)*cos(v), sin(u)*cos(v), sin(u)

## How it works…

As in the previous recipe, we provide the x, y, and z components, but the provision of components that depend on both parameters (u and v) defnes a surface rather than merely a path through the 3D space.

## There's more…

The same thing can be done with colored surfaces.

The previous figure is of the same function that we plotted in the one prior to it, rendered as a color-coded surface rather than a wireframe. Note that although the axes are visible through the surface, the surface is hidden by itself. Following is the script that produced the previous figure:

set param

set iso 50

set ztics .5

set xtics .4

set ytics .4

set urange [-pi:pi]

set vrange [-pi:pi]

set pm3d depthorder

splot cos(u)*cos(v), sin(u)*cos(v), sin(u) with pm3d

We've added something to the splot command with pm3d. We also set a special pm3d option with set pm3d depthorder. This option causes gnuplot to draw the surface starting with the elements farthest away from our viewpoint, which simulates hidden line removal and renders the surface as if it were opaque, making it much easier to understand visually.

# Summary

In this article, we broke into the third dimension. The graphs were visualizations of quantities that depend on two variables; they are expressed as surfaces, contours, felds of arrows, paths in space, or as a combination of these elements. Through this article we have learnt how to plot surfaces, vectors, heat maps, and lines in a 3D space.

## Post new comment