Download presentation
Presentation is loading. Please wait.
Published byPeregrine Townsend Modified over 9 years ago
1
GRAPHICS Graphics is one of the places where the computing world has not yet agreed on standard, and so instead there are a dozen standards, including JPG, PNG, PDF GIF, and many other TLAs logging in remotely to a command-line at the university’s servers, that support only SVG graphics. Some journals insist on all graphics being in EPS format, and others require JPGs and GIFs. The solution to the graphics portability problem is to use a handful of external programs, easily available via your package manager, that take in plain text and output an image in any of the panoply of graphics formats. The text-to-graphics programs here are as open and freely available as gcc,
2
The plot-producing program with which this chapter will primarily be concerned is Gnuplot. Its language basically has only two verbs—set and plot—plus a few variants (unset, replot, et cetera)
3
Introduction to gnuplot --- Basic Use
Since gnuplot has been ported to various operating systems, its usage slightly depends on the platform. Here we describe an introduction to gnuplot for the case of UNIX, X11. Basically its usage is common to those systems, so that this tutorial may be helpful for the other operating systems. First of all, exec gnuplot. Gnuplot displays a banner and credit, then shows a gnuplot command line prompt "gnuplot> ". Gnuplot is a command line driven plotting tool. You give commands here to make your figure.
5
At the "gnuplot> " prompt you can use the following commands:
Commands to Quit, Read a Command File, and Save Parameters exit or quit command terminates gnuplot. Once you quit gnuplot, all of setting you made will be lost. To save the current setting, use save command followed by a file name in which parameters and functions you defined are stored. The file name is quoted by a single or double quotation. The file name is arbitrary, but if the same name exists in the current directory, gnuplot overwrites internal parameters in that file without any warnings gnuplot> save "savefile.plt“ The saved file is a usual text file. You can edit the contents with a text editor
6
To draw a graph again with this file, use the load "savefile
To draw a graph again with this file, use the load "savefile.plt" command at the gnuplot command-line, or execute gnuplot and give the data-file name as a command line option. Inside gnuplot gnuplot> load "savefile.plt" Outside gnuplot (shell command line) % gnuplot savefile.plt
7
There are two basic commands to plot a graph, plot and splot
There are two basic commands to plot a graph, plot and splot . The former is used for a 2-dimensional graph, and the latter is for a 3-dim. Gnuplot makes a graph of any kinds of functions or numerical data stored in a file. To plot a function, use the plot/splot command with a range of X-axis (or X and Y ranges for 3-dim. plot) and the function. You can omit the range parameters. Here is an example of plotting y=sin(x) gnuplot> plot sin(x) This is the 2-dimensional graph gnuplot generates. The frame is drawn by a thick line, which is called "border". The X and Y axes have graduation called "major tics", and numeric labels are written at the tics location. The intervals between each major tic can be divided by minor tics. You can draw names of X and Y axes. The X-axis name -- "xlabel" -- is shown below the x-axis border, while the position of "ylabel" depends on your terminal
9
If ranges of X and Y axes are not specified, gnuplot determines appropriate values for those automatically. The example above you can see the default X range which is -10 to +10, and the Y range was automatically determined. To set the X range 0 to 5, [0:5] gnuplot> plot [0:5] sin(x)
11
Commands to change variables and parameters
There are a number of parameters which change your plot appearance. You can change them by the set command. See online help
12
Firstly insert some text into the xlabel and ylabel
Firstly insert some text into the xlabel and ylabel. The text should be quoted by a single or double quotation. Next, specify the range of X and Y axes. As explained above the X range can be changed if you specify that at plotting. Alternatively you can change them by the "xrange" and "yrange" parameters. gnuplot> set xlabel "X-AXIS" gnuplot> set ylabel "Y-AXIS" gnuplot> set xrange [0:5] gnuplot> set yrange [-2:2] gnuplot> plot sin(x)
14
If a terminal is not specified, gnuplot makes a graph on your screen
If a terminal is not specified, gnuplot makes a graph on your screen. The set terminal command changes the destination of your plot into a postscript file or printer, etc. Gnuplot produces a variety of graph by means of various drivers, so that it is independent of the platforms (but quality of the drawing still depends of the terminal). The terminals which your gnuplot can handle can be displayed by the set terminal command.
15
Gnuplot produces a graph in a Postscript format when set terminal postscript command is given. If an output direction is not specified, the produced Postscript data flow on your screen. The set output command changes the destination of output.
16
The set output command changes the destination of output
gnuplot> set output "plot.ps" gnuplot> plot sin(x)
17
Commands for Substitution, Function Definition, Calculations, etc.
You can use gnuplot as a simple calculator. To substitute a value into a variable, just type "variable = value" at the gnuplot command line. To see the value of variable, use print command. gnuplot> a=10 gnuplot> print a 10 "Variable = expression" substitutes a calculated value into the variable. Double precision is used for the calculation except for integer. gnuplot> a=1+2*sqrt(3) gnuplot> print log(a)
18
The defined variable can be used for the plot command
The defined variable can be used for the plot command. Gnuplot holds the circular constant in "pi". To draw a graph of a*sin(x) from -2pi to +2pi, where a=0.5: gnuplot> set xrange [-2*pi:2*pi] gnuplot> a=0.5 gnuplot> plot a*sin(x)
20
You can define your own function
You can define your own function. For example, to make a function of f(x)=sin(x)*cos(x), it is defined as: gnuplot> f(x)=sin(x)*cos(x) The function defined above can be referred to as "f(x)". You can also include a user-defined variable in your function. gnuplot> f(x)=a*sin(x)*cos(x) This function contains a variable "a" which is defined by user, and the function varies with this parameter.
21
Preparation of Data File
Here is an example for plotting of numerical data which are generated by numerical calculations. To do it, the calculated results should be stored in a data-file that is a usual text file. The following programs calculate a Pade approximation of y=exp(-x)
24
Those programs give the following output
Those programs give the following output. The first column is X-coordinate, the second is a direct calculation of EXP(-X), the third and forth columns are the Pade approximation with different orders. As you can see, this approximation is only valid for small X values
25
Plot (X,Y) Pairs Data file "output.dat" contains the calculated values above. Each X-value has 3 different Y values in this case. To draw the second column (calculated EXP(-X) values) as a function of the first column, use using keyword at plotting. gnuplot> plot "output.dat" using 1:2 with lines
27
style of graph is specified by the with keyword
style of graph is specified by the with keyword. In the example above, lines style is given, with which each data point is connected by small lines. There are several kinds of line-styles those are numbered by 1, 2, 3... To change the line style, with lines is followed by the line-style number. If the number is not given, gnuplot assigns numbers automatically from 1 to a certain maximal number.
28
There are several plot-styles --- draw symbols, connect with lines, connect with step-like lines, draw bars, etc.
29
Draw Several Lines Next, the third and fourth columns are plotted on the same figure. To draw several lines simultaneously, repeat the data specification like -- plot "A" using 1:2 with line, "B" using 1:2 with points, ... Sometimes such a command line becomes very long. If a line is ended with a character '\', the next line is regarded as a continuous line. Don't put any letters after the back-slash. gnuplot> plot "output.dat" using 1:2 with lines, \ > "output.dat" using 1:3 with lines,\ > "output.dat" using 1:4 with lines
31
In the figure legend, the data-file name and the column numbers those were used for plotting were indicated. The red line is obtained by an analytical function, so let's change the first line of the legend into "Analytical". The next green line is a result of Pade approximation with L=1 and M=2, so that "L=1, M=2" should be displayed. The blue line is also the result of "L=2, M=2" Pade approximation. gnuplot> plot "output.dat" using 1:2 title "Analytical" with lines, \ > "output.dat" using 1:3 title "L=1, M=2" with lines,\ > "output.dat" using 1:4 title "L=2, M=1" with lines
33
Insert a Graph Title and Axis Names
Now, let's insert X and Y axis names. The name of X axis is just "x", while the Y axis is "y=exp(-x)". To set those names, use the set xlabel and set ylabel commands. In addition, you can put a title of this figure, "Pade approximation", by the set title command. With the replot command, you can omit a long plot command. gnuplot> set xlabel "x" gnuplot> set ylabel "y=exp(-x)" gnuplot> set title "Pade approximation" gnuplot> replot
35
Change the X and Y Axes Range
Now let's change the X and Y ranges. Set the Y-range [0,1], and the X-range [0,2]. gnuplot> set xrange [0:2] gnuplot> set yrange [0:1] gnuplot> replot
37
Put Graduations The graduations on the X-axis starts with 0, and the interval is 0.5. To change the graduations (tics), use set {x|y}tics . The tics can be controlled by three optional numbers. If there is a one number followed the set tics command, like set xtics 10 , this number "10" is regarded as an increment. If there are two figures, the first one is the initial value, and the second is the increment. If three, the last one becomes the final value. You can also divide the interval which is given as an increment by the set tics command, and draw small tics inside the interval with the set m{x|y}tics n command, where n is the number of division. gnuplot> set xtics 1 gnuplot> set mxtics 5 gnuplot> set ytics 0.5 gnuplot> set mytics 5 gnuplot> replot
39
Then we make the graph in a Postscript format, and print it
Then we make the graph in a Postscript format, and print it. Firstly change the terminal into "postscript", and specify a name of output file. Before quit gnuplot, save your parameters and other setup into a file (output.plt ) gnuplot> set term postscript gnuplot> set output "output.ps" gnuplot> replot gnuplot> save "output.plt" gnuplot> quit The file 'output.ps' can be browse with a Postscript viewer like 'gv' or 'ghostview', and you can print this file with a Postscript printer. The following image is our Postscript data 'output.ps' displayed with ghostview.
41
When you plotted the graph on your screen, the first line was a red line. However it turned into the solid line here. The blue and green lines became the dashed lines. (Though it is hard to see them in a small size image.) As you can see above, line and symbol types depend on the terminal you use. In order to know which line number corresponds to the solid, dashed, dotted, etc. try test . For example, on the X window system, you get: gnuplot> set term x11 gnuplot> test
43
setpointtype,setlinetype
You can set the width and colors of your lines, and whether your points will display as balls, triangles, boxes, stars, et cetera. The pointtypeand linetypecommands, among a handful of other commands, may differ from on-screen to Postscript to PNG to other formats, depending upon what is easy in the different formats. You can see what each terminal can do via the testcommand. E.g.: set terminal postscript set out ’testpage.ps’ test
44
Comments Gnuplot follows the commenting standards of many scripting languages: everything on a line after a # is ignored. For example, if a script begins with #set terminal postscript color #set out'printme.eps' then these lines are ignored, and Gnuplot will display plots on the screen as usual. If you later decide to print the plot, you can delete the #s and the script will write to printme.eps.
45
replot You will often want multiple data sets on the same plot, and Gnuplot does this easily using the replot command. set xrange [−4:6] plot sin(x) replot cos(x) replot log(x) + 2*x − 0.5*x**2 Gnuplot always understands the variable x to refer to the first axis and y to the second. If you are doing a parametric plot, then you will be using the variables t, u, and v Gnuplot knows all of the functions in the standard C math library. For example, the above sequence will produce a set of pleasing curves. Notice that x**2is common math-package notation for x2 .
46
splot The plot command prints flat, 2-D plots. To plot 3-D surfaces, use splot. All of the above applies directly, but with three dimensions. If your data set has three columns, then you can plot it with splot'datafile'. If your data set has more than three columns, then specify the three you want with a form like splot 'datafile'using1:5:4. Surface plotting goes hand-in-hand with the pm3d(palette-mapped 3-D) option, that produces a pleasing color-gradient surface simple example that produces the sort of plot used in advertisements for math programs. Again, if you run this from the Gnuplot prompt and a system that supports it, you should be able to use the mouse to spin the plot.
47
set pm3d splot sin(x) *cos(y) with pm3d
48
1 set term postscript color;
2 set out ’plot.eps’; 3 set pm3d; #for the contour map, use set pm3d map; 4 unset colorbox 5 set xlabel ’percent acting’; set ylabel ’value of emulation (n)’; 6 set palette gray; 7 set xtics (’0’ 0,’0.25’ 250,’0.5’ 500,’0.75’ 750, ’1’ 999); 8 set ytics (’0’ 0, ’0.2’ 1, ’0.4’ 2, ’0.6’ 3, ’0.8’ 4, ’1’ 5, ’1.2’ 6) 9 splot ’datafile’ matrix with pm3d
50
Lines one and two send the output to a Postscript file instead of the screen. Given line six, the color modifier is optional in this case. • Line three tells Gnuplot to prepare for a palette-mapped surface, and is necessary before the splotcommand on line nine. • Line four deletes the legend, which in the pm3d case is known as the colorbox. • Line five sets the labels, and demonstrates that Gnuplot commands may put each either on a separate line or separated with a semicolon Line six sets the color scheme to something appropriate for a book printed in black and white. Lines seven and eight fix the axis labels, because Gnuplot defaults to using the index of the column or row as the label
51
Set point type,setline type
You can set the width and colors of your lines, and whether your points will display as balls, triangles, boxes, stars The point type and line type commands, among a handful of other commands, may differ from on-screen to Postscript to PNG to other formats, depending upon what is easy in the different formats. You can see what each terminal can do via the testcommand. E.g.: set terminal postscript set out ’testpage.ps’ test
52
Set key How do I erase a legend ?
There are two ways. The first one is, gnuplot> set nokey and the other one is to use the notitle key word at plotting. In the case below, the data file has a legend but the function does not. gnuplot> plot f(x) notitle, "file.dat" title "data"
53
How do I change the location of legend ?
Usually a legend appears at the top/right corner int the graph. You can change the position with the set key command. If you give the command, gnuplot> set key left bottom the legend goes to left/bottom. Available options are, left, right, top, bottom, outside, and below. You can combine some of them. For example, outside bottom. It is possible to set the position of legend directly. If you want to move it to the position (X,Y)=(100,100), gnuplot> set key 100,100 The coordinate (100,100) is the position of the mid-point between a text and a line/symbol of the first line of the legend. The coordinate is the system defined by the X and Y axes. If you want to place the legend independently of the axes, .
54
3d Plots set xrange[0:7] set yrange[1:5]
splot exp(-0.2*x)*cos(x*y)*sin(y)
55
You can increase the number of lines in the plot with the set isosamples command.
set xrange[-3:7] set yrange[1:5] set isosamples 30 splot exp(-0.2*x)*cos(x*y)*sin(y)
56
Hidden lines It is also possible to remove lines that would be hidden if the surface was not transparent. This can make complicated diagrams easier to understand set xrange[-3:7] set yrange[1:5] set isosamples 30 set hidden3d splot exp(-0.2*x)*cos(x*y)*sin(y)
58
Contours It is also possible to draw contours on the plot. using the set contour <base|surface|both> eg set contour surface which makes gnuplot draw contours on the surface. the base option make the contours get drawn in the base, and both draws them in both places. set xrange[-3:4] set yrange[1:5] set isosamples 30 set hidden3d set key outside set contour both splot exp(-0.2*x)*cos(x*y)*sin(y) notitle
60
Often one simply wants the contour plot as viewed from above to do this use
set view map unset surface The unset surface prevents the surface from being drawn, as from above it is just a grid. set xrange[-3:4] set yrange[1:5] set isosamples 50 set view map unset sureface set hidden3d set key outside set contour base splot exp(-0.2*x)*cos(x*y)*sin(y) notitle
62
Colouration with pm3d It is quite nice to colour shade the surfaces of plots with shades that depend on the height in the z direction. to do this use set pm3d set pm3d has a number of options which affect the appearances of the plots. For example set xrange[-2:2] set yrange[-2:2] set isosamples 50 set pm3d unset surface set key outside splot exp(-0.2*x)*cos(x*y)*sin(y) notitle
64
It is also nice to use the coloration with contour plots.
set xrange[-2:2] set yrange[-2:2] set isosamples 50 set pm3d unset surface set view map set contour set key outside splot exp(-0.2*x)*cos(x*y)*sin(y) notitle
66
You can play with the colour scheme used in the plot
You can play with the colour scheme used in the plot. If you are going to print the plot on a monochorme printer, it is useful to use set palette gray negative This chooses a gray palette for the colouring. The negative reverses the order, making black represent higher values and white the lower values. There are many more options to the set palette command see help system for details. set xrange[-2:2] set yrange[-2:2] set isosamples 50 set pm3d unset surface set view map set contour set key outside set palette gray negative splot exp(-0.2*x)*cos(x*y)*sin(y) notitle
68
The scripts above gave a file name from which to read the data (plot'data-debt'). Alternatively, plot'-'tells Gnuplot to plot data to be placed immediately after the plotcommand. With the '-'trick, the process of turning a matrix into a basic plot
69
Write to a file FILE * f = fopen("plot_me", "w"); 2 if (!f) exit(0);
3 fprintf(f, "set key off; set ylabel ’picograms/liter’\n set xrange [−10:10]\n"); 4 fprintf(f, "plot ’−’ using 1:5 title ’columns one and five’\n"); 5 fclose(f); 6 apop_matrix_print(data−>matrix, "plot_me");
70
Instant gratification
The above method involved writing your commands and data to a file and then running Gnuplot, but you may want to produce plots as your program runs. This is often useful for simulations, to give you a hint that all is OK while the program runs, This is easy to do using a pipe The command popendoes two things: it runs the specified program, and it produces a data pipe that sends a stream of data produced by your program to the now-running child program. Any commands you write to the pipe are read by the child as if someone had typed those commands into the program directly
72
The popenfunction takes in the location of the Gnuplot executable, and a w to indicate that you will be writing to Gnuplot rather than reading from it. Most systems will accept the simple program name, gnuplot, and will search the program path for its location. If gnuplotis not on the path, then you will need to give an explicit location like /usr/local/bin/gnuplot. In this case, you can find where Gnuplot lives on your machine using the command which gnuplot. The popenfunction then returns a FILE*, here assigned to gp.
73
Since gp was declared to be a static variable, and popenis called only when gp==NULLIf gp is NULLafter the call to popen, then something went wrong. This is worth checking for every time a pipe is created. But if the pipe was created properly, then the function continues with the now familiar process of writing plot'-'and a matrix to a file. The resetcommand to Gnuplot (line 11) ensures that next time you call the function, the new plot will not have any strange interactions with the last plot Lines 12 and 13 set the output type to 'p'and the output pipe to gp; apop_-matrix_print uses these global variables to know that it should write to that pipe instead of a file or stdout. The function on line 15, fflush, tells the system to send all elements of the gpbuffer down the pipeline.
74
Self-executing files The first line of the script must begin with the special marker #! followed by the interpreter that will read the file, and the script must be given execute permissions. Listing 5.4 shows a program that produces a self-executing Gnuplot script to plot sin(x). You could even use system("./plotme")to have the script execute at the end of this program.
75
#include <apop.h> #include <sys/stat.h> //chmod
Write to a file that becomes a self-executing Gnuplot script. Run the script using ./plot_mefrom the command line. #include <apop.h> #include <sys/stat.h> //chmod int main(){ char filename[] = "plot_me"; FILE * f = fopen(filename, "w"); fprintf(f, "#!/usr/bin/gnuplot −persist\n\ plot sin(x)"); fclose(f); chmod(filename, 0755);
76
A SAMPLING OF SPECIAL PLOTS
for a system that basically only has a setand a plotcommand, Gnuplot is surprisingly versatile. Here are some specialized visualizations that go well beyond the basic 2-D plot. LATTICES Perhaps plotting two pairs of columns at a time is not sufficient—you want bulk, displaying every variable plotted against every other. For this, use the apop_plot_latticefunction #include "eigenbox.h" int main(){ apop_plot_lattice(query_data(), "out"); }
77
ERROR BARS The typical error bar has three parts: a center, a top limit, and a bottom limit. Gnuplot supports this type of data directly, via setstyle dataerrorbars Figure 5.8, takes the second approach, querying out a month, the mean temperature for the month, and the standard deviation of temperature for the month. Plotting the data shows both the typical annual cycle of temperatures and the regular fluctuation of variances of temperature.
78
#include <apop.h>
int main(){ apop_db_open("data−climate.db"); apop_data * d = apop_query_to_data("select \ (yearmonth/100. − round(yearmonth/100.))*100 as month, \ avg(tmp), stddev(tmp) \ from precip group by month"); printf("set xrange[0:13]; plot ’−’ with errorbars\n"); apop_matrix_show(d−>matrix); }
80
HISTOGRAMS A histogram is a set of X- and Y-values like any other, so plotting it requires no special tools. However, Gnuplot will not take a list of data and form a histogram for you—you have to do this on the C-side and then send the final histogram to Gnuplot. Fortunately, apop_plot_histogram does the binning for you.
81
LOG PLOTS You can plot your data on a log scale by either transforming it before it gets to Gnuplot or by transforming the plot. Log plots work best on a log-base-10 scale, rather than the typical natural logarithm, because readers can immediately convert a 2 on the scale to 1e2, a −4 to 1e−4, et cetera. From C, you can use the log10(x)function to calculate log 10 x,and if your data is in a gsl_vector, you can use apop_ve tor_log10to transform the entire vector at once. In Gnuplot, simply setlogscaley to use a log-scaled Y axis, setlogscaleX to use a log-scaled X axis, or setlogscalexy for both.
82
PRUNING AND JITTERING Plotting the entire data set may be detrimental for a few reasons. One is the range problem: there is always that one data point at Y = 1e20 throws off the whole darn plot. If you are using an interactive on-screen plot, you can select a smaller region, but it would be better to just not plot that point to begin with. The second reason for pruning is that the data set may be too large for a single page. The black blob you get from plotting ten million data points on a single piece of paper is not very informative. In this case, you want to use only a random subset of the data
83
Both of these are problems of selecting data, and so they are easy to handle via SQL. A simple sele ct*fromplotmewherevalue<1e7will eliminate values greater than a million In Gnuplot, you can add the every keyword to a plot, such as plot'data‘ every 5to plot every fifth data point
84
consider graphing the number of tattoos a person has against her year of
birth. Because both of these are discrete values, we can expect that many people will share the same year of birth and the same tattoo count, meaning that the plot of those people would be exactly one point.
86
One solution is to add a small amount of noise to every observation, so that two points will fall exactly on top of each other with probability near zero. Figure 5.9 shows such a plot. Without jittering, there would be exactly one point on the onetattoo column for every year from about 1955 to 1985; with jittering, it is evident that there are generally more people with one tattoo born from 1965–1975 than in earlier or later years, and that more than half of the sample with two tattoos was born after 1975.
87
ANIMATION Perhaps three dimensions is not quite enough, and you need one more. Gnuplot easily supports animation: just stack matrices one after the next and call plot in between There are two details that will help you with plotting multiple data sets. First, Gnuplot reads an ealone on a line to indicate the end of a data set. Second, Gnuplot allows you to define constants via a simple equals sign; e.g., the command p= 0.6 creates the variable pand sets it to 0.6. Third, Gnuplot has a pause pcommand that will wait p seconds before drawing the next plot. If a one-second pause is too long or too short, you only need to change the single value of pat the head of the file to change the delay throughout.
89
GRAPHS—NODES AND FLOWCHARTS
The mathematician’s definition of graph, however, is a set of nodes connected by edges, as in Figure Gnuplot can only plot; if you have network data that you would like to visualize, Graphviz is the package to use. The package includes various executables, the most notable of which are dot and neato. Both take the same input files, but dotproduces a flowchart where there is a definite beginning and end, while neatoproduces more amorphous plots that aim only to group nodes via the links connecting them
90
digraph { rankdir = LR; node [shape=box]; "Data" −> "Estimation" −> "Parameters"; } The lines with =in them set parameters, stating that the graph should read leftto-right instead of the top-to-bottom default, and that the nodes should be boxes instead of the default ellipses. The line with the ->s defines how the nodes should link,
91
At this point, you have all the tools you need to autogenerate a graph
At this point, you have all the tools you need to autogenerate a graph. For example, say that you have an n × n grid where a one in position (i, j ) indicates a link between agents i and j and a zero indicates no link. Then a simple for loop would convert this data into a neato-plottable file, with a series of rows with a form like, e.g., node32->node12
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.