gnuplot draw 3d curve from function

Plotting Data with gnuplot

This tutorial is intended as a supplement to the data contained on the Physics' Department website: Plotting and Fitting Data and Plotting Data with Kaleidagraph. It shows how to perform the same functions described in those tutorials using gnuplot, a command-line-driven plotting program ordinarily bachelor on Unix machines (though available for other platforms as well). Yous may observe it helpful to look at the other tutorials as well; this one is intended to follow them quite closely.

The instructions and samples given correspond to version iii.7 running nether Linux, but the results should be like everywhere. If yous are using an older version, notwithstanding, you might find a few of the more than advanced features missing.

Introduction

gnuplot seems almost the antithesis of Kaleidagraph: the the Kaleidagraph tutorial calls Kaleidagraph "an piece of cake-to-use if somewhat limited graphics program". gnuplot is a not-quite-as-like shooting fish in a barrel-to use, though extremely powerful, command-line plotting programme.

Running gnuplot is piece of cake: from a command prompt on any organization, type gnuplot. It is even possible to do this over a telnet or ssh connection, and preview the graphs in text style! For best results, however, you should run gnuplot from within X Window, then that you tin encounter better previews of your plots.

Entering Information

All the data sets you apply in gnuplot should exist typed into a text file first. There should be one information indicate per line. Each data betoken will consist of several numbers: the independent variable, the dependent variable, and optionally mistake bars. Each of these fields should be separated by a tab.

Actually, any number of fields may be specified on each line; this is useful if you have multiple measurements for each data bespeak, for instance. For information about how to admission this additional information in your plots, encounter (fixme: add section) below.

Y'all may include any extra data you want in the file, such every bit a description of the data, headings for each of the data columns, and so on, equally long as each such line begins with the comment graphic symbol, #.

The dataset used in this case is available in the file cavendish.data.

Plotting Functions

Basic Plotting

Plotting functions in gnuplot is really quite easy. Suppose you want to plot the role f(x) = exp(-10^two / ii). In gnuplot, exponentiation uses **, not ^. So, after starting up gnuplot, at the gnuplot> prompt you would type:

plot exp(-x**2 / 2)      

Usually, y'all'll want a lilliputian more control over your plot, at least specifying the ranges for the x- and y-axes. You can specify these in a [minimum:maximum] form earlier the function. Specify the 10 range commencement, then the y range. You may exit off the y range, or both. We tin can revise our previous plot command to:

plot [-4:4] exp(-x**2 / two)      

Hither, the y range volition exist automatically adamant.

More Function Plotting

If you'd like to plot more than than one function, only list all the functions, separated by commas. For case:

plot [-4:4] exp(-x**2 / 2), x**2 / xvi      

You can also rename the independent variable, if yous'd like. This is done in conjuction with specifying the plot range:

plot [t=-iv:4] exp(-t**ii / 2), t**2 / xvi      

Defining Functions

Sometimes, it may be user-friendly to define a function, so that it does not take to be retyped each time. It's easy to do this. Let's create a function f(x) to represent our bong curve, then use it in the plot:

f(10) = exp(-10**2 / 2) plot [t=-4:4] f(t), t**two / sixteen      

Plot Titles, Labels, and Legends

You might have noticed that when you produced your plots, a legend was automatically created in the upper-right corner of the plot. By default, the name of each curve is simply the formula you typed in. You can give them other names using the title attribute. Just follow the formula for the function with championship "The Championship". We can modify our previous command to:

plot [t=-4:iv] f(t) championship "Bong Bend", t**2 / 16 championship "Parabola"      

Note that commas are never used except to split distinct functions. If you would like a curve not to show up in the legend, set its championship to "".

We can as well add together a title to our plot, and some labels on the axes. The set up command is used. Here is an example:

gear up title "Some Sample Plots" ready xlabel "Independent Variable (no units)" ready ylabel "Dependent Variable (no units)"      

These changes do not take an effect until yous redraw the plot. This tin can be washed past typing in the plot command once more, but if the plot itself does non change, it is enough to type:

replot      

to replot the last functions given.

Other Prissy Touches

It's often squeamish to add a grid to the plot, making it easier to see where functions and information fall on the plot. To do this, type

ready grid      

Plotting Data

After learning how to plot functions, at present it's time to acquire how to plot data. The syntax is almost the same, except that instead of specifying a function, you must specify the name of the file containing the data to plot, enclosed in double quotes.

First, since we were playing around with plots in a higher place, nosotros'll clear the labels on the axes and other settings:

reset      

Y'all could likewise quit gnuplot and restart it for the aforementioned upshot. Now, we'll plot our sample data. We'll go rid of an entry in the fable for our data points past using a title of "", and also set up the axes on the plot:

set title "Cavendish Data" ready xlabel "Time (due south)" set ylabel "Bending (mrad)" set up grid plot "cavendish.data" title ""      

When plotting data, it usually isn't necessary to specify ranges for the independent and dependent variables, since they can exist figured out from the input. If necessary, of class, you can ever give them.

Including Fault Bars

Since our input data contains uncertainties for the measured (dependent) quantity, we can create y mistake bars. Once again, gnuplot makes this piece of cake:

plot "cavendish.data" championship "" with yerrorbars      

It's possible to plot ten fault bars using xerrorbars, or both x and y errorbars using xyerrorbars. When both x and y error bars are used, there must be four columns present, and x fault bars must be specified offset in the data file. More variations are possible; see the online assist for more information.

Note that gnuplot tin be very picky about the club yous requite modifiers to the plots. If you were instead to type

plot "cavendish.data" with yerrorbars title ""      

You'd become a rather foreign error message: undefined variable: championship. If you see error messages like this, check the ordering in your plot commands. If you're unsure, typing assistance plot should get y'all straightened out.

Plumbing fixtures Information

No plotting program would be consummate without the ability to fit our data to a curve. For the Cavendish experiment, nosotros'll demand to fit our data to a sinusoidal curve with exponential decay. gnuplot supports these nonlinear curve fits, and tin even have the experimental uncertainties of the information points into account.

First, it's necessary to define the form of the function nosotros'll try to fit to. Ascertain this as yous would any other part in gnuplot, merely leave variables for the plumbing equipment parameters. We'll utilise

theta(t) = theta0 + a * exp(-t / tau) * sin(2 * pi * t / T + phi)      

The various fitting parameters are:

  • a: the amplitude of oscillations
  • tau: the period of oscillation
  • phi: the initial stage
  • T: exponential disuse time
  • theta0: shift from equilibrium position

For a non-linear curve fit such every bit this, information technology is ofttimes necessary to provide an initial approximate for each of the plumbing equipment parameters, or the fitting try may fail. For elementary equations, such as polynomials, this volition non be necessary (merely never hurts).

a = xl tau = 15 phi = -0.5 T = 15 theta0 = 10      

Finally, we'll practice the actual curve fit. The syntax for this is:

fit theta(ten) "cavendish.data" using 1:2:3 via a, tau, phi, T, theta0      

Hither'south how the command is interpreted: fit tells gnuplot we're doing a curve fit. The next part, theta(x), must be a part that we're using to fit the data. Here we must apply ten as the independent variable. The next part, "cavendish.data", must be a datafile containing the data we wish to fit. The using 1:2:3 tells gnuplot to accept columns 1, 2, and 3 from the data file and use them as the x, y, and uncertainties, respectively. If this office is left out, so the experimental uncertainties will not exist used for the curve fit. Encounter below for a greater discussion of the extremely powerful using qualifier. Finally, we must tell gnuplot what variables information technology tin adapt to get a ameliorate fit. For this example, we say via a, tau, phi, T, theta0.

gnuplot will produce output as it proceeds through the fit, and if the fit is successful yous should see something similar this:

degrees of freedom (ndf) : 34 rms of residuals      (stdfit) = sqrt(WSSR/ndf)      : ane.07102 variance of residuals (reduced chisquare) = WSSR/ndf : 1.14708  Final set of parameters            Asymptotic Standard Error =======================            ==========================  a               = 44.5389          +/- 2.127        (4.776%) tau             = 57.5667          +/- viii.132        (14.13%) phi             = -0.377254        +/- 0.04235      (xi.22%) T               = 13.1026          +/- 0.06465      (0.4934%) theta0          = ii.45704          +/- 0.6081       (24.75%)   correlation matrix of the fit parameters:                 a      tau    phi    T      theta0  a               1.000  tau            -0.844  1.000  phi            -0.100  0.088  one.000  T              -0.072  0.072  0.806  1.000  theta0         -0.166  0.127 -0.182 -0.166  i.000      

Of import quantities to notation are the reduced chi square (variance of residuals), which in this case is 1.15, and the values for each of the fitting parameters. Each plumbing equipment parameter besides has an uncertainty listed. The correlation matrix at the end can ususually be ignored.

gnuplot has also stored the fitting parameters in the variables, and then producing a plot with the associated best-fit bend is as easy as:

plot "cavendish.data" championship "" with yerrorbars, theta(x) title "Best-Fit Curve"      

More Advanced Features

Using using

The using qualifier used in the fitting control above is an extremely powerful tool in gnuplot. With information technology, you lot can do most limitless command over your data equally it is plotted.

gnuplot usually expects a certain number of data columns when it uses a data file (whether for plotting or plumbing equipment). Usually, simply ii columns are used: the independent variable and the dependent variable. With error bars, one or 2 more than columns may be used. Usually, these columns are taken out of the datafile directly. Sometimes, it's necessary to exercise a footling more control. That's where using comes in.

Say you demand to swap the two data columns, since that the dependent variable comes start, followed past the independent variable in the data file. You lot can produce this plot with the command:

plot "reversed.data" using 2:1      

The using command expects several values, one for each column of data required, with each value separated by a colon. If the value is only a number, gnuplot volition take that information piece from the specified column in the datafile. In this case, nosotros tell gnuplot to take the independent variable from column 2, and the dependent variable from column 1.

The previous instance was a bit contrived. Merely there'southward a very common instance where using is used: when there are multiple data sets in an input. Suppose you take a datafile with 3 columns: an independent variable, and two dependent variables. You lot'd like to plot both dependet variables every bit a separate fix of points. You tin employ:

plot "double.information" using i:2 title "Series i", "double.data" using i:three championship "Series two"      

In our plumbing equipment case above, by specifying using 1:2:three, nosotros were forcing the fit command to accept three columns every bit input, instead of the usual ii (to include the error information), just we did not perform any reordering on them.

This is still just scratching the surface of what using can do. Instead of giving a column number, y'all can as well specify a complete expression, which must exist surrounded in parentheses. Inside this expression, the values from the columns can be accessed as $one, $2, $3, etc. As an example, if we wanted to plot the natural logarithm of our dependent variable, we could utilise:

plot "log.data" using 1:(log($2))      

Notation that as function of a using qualifier, ($ii) is exactly equivalent to 2.

For another case, come across the next department: plotting residuals.

Plotting Residuals

To understand this section, you'll need to have understood the section "Using using" to a higher place.

First, nosotros'll produce a plot of the difference between each information point and the fitted curve:

plot "cavendish.data" using 1:(theta($1) - $2):3 title "Residuals" with yerrorbars      

A little explanation of the using statement is perhaps in social club. We're producing a plot with y error confined, and then we need three data columns. Hence, the using qualifier has 3 parts, separated by colons. The first, one, says the get-go part, the independent variable, is but the first cavalcade from the input file. The second part is an expression: we'll compute the difference between our function (theta), evaluated at the value for the independent variable ($1 - start cavalcade of data file), and the measured value ($2 - second column of data file, or dependent variable) for that signal. The third column, 3, simply says to apply the existing uncertainty stored in column 3 of the data file with no modification.

It would be even better if we could put the residuals on the same graph equally the fitted curve. To make this look proficient, we'll utilise a different calibration for the residuals, so they tin be separated from the rest of the graph. gnuplot allows yous to utilise two different scales for each axis: there are independent ten and x2 scales for the x-axis, y and y2 scales for the y-axis, etc.

There'south some other syntax for defining the ranges for each of the axes, which is necessary for using more than one scale at a time. First, let'due south shift the graph of our data and fitted curve upwards a bit, to brand room.

fix yrange [-eighty:lx] plot "cavendish.data" title "" with yerrorbars, theta(ten) championship ""      

This is like specifying the range as office of the plot command, but the settings will stick around until they are overridden, and nosotros tin specify a y-range without an x-range.

At present, we'll create a second scale for the y-centrality on the correct-hand side. This tin be accomplished past:

ready y2range [-20:120] prepare y2tics border      

The set y2tics border command tells gnuplot to brandish this scale on the edge of the plot. Without it, the new scale would be set, just it would not be shown on the correct-hand side of the plot.

Now it'southward time to add our residuals. We add them to the plot control, and specify that they should utilise the new y calibration. They will use the same x scale equally before:

plot "cavendish.data" championship "" with yerrorbars, theta(ten) title "", "cavendish.data" using 1:(theta($1) - $ii):3 axes x1y2 championship "" with yerrorbars      

Hither, axes x1y2 means to use the normal x-axis, and the new y axis we merely defined.

Finally, for a little extra touch, let's draw an x-axis for the residuals:

gear up x2zeroaxis lt -i set y2label "Residuals" replot      

Here, lt -1 stands for "line type -1", where -1 is the style unremarkably used for plot borders.

If you've been following along the unabridged tutorial, you should now have a plot window that looks something like this:

[Plot Preview Window]

Producing Printed Output

gnuplot is very device-neutral: when producing your plots, it could intendance less whether it is producing a preview on an X Window brandish, an ASCII-art version for a terminal, or whatsoever other output class. The plot commands will all work the same. After getting your plot the fashion y'all like it, however, you'll want to salvage it or impress it out. To exercise and then, you lot'll desire to change the output format, which tin be achieved with the set term command.

When running in X, the default concluding type is x11. If, after saving output elsewhere, you want to preview output in Ten again, you'll desire to blazon

gear up term x11      

If you are working over telnet or where graphics are non available, you can type

set term dumb      

to choose the dumb concluding. While not pretty, you can often become an thought what your plot looks like with this. The Cavendish data looks like this on a impaired concluding:

        Cavendish Data Bending (mrad)                                                         Residuals   60 ++------+--------+-------+--------+-------+--------+-------+-------++120      +    * *+        +       +        +       +        +       +        +      |    A#A#  *     :       :        :       :        :       :        |   40 ++...#..#A.A................#*#.........................*..........++100      |   A   : #*     :       : A AA## :       :      *#A#** A  :        |   20 ++.#......##.............A#*..*.A#..............*A...AA.*..........++fourscore      | *     :   #    :       *      * A       :    #A  :   #*  :        |      |#A     :   A    :      #:        # *     :   A#   :    #* :        |    0 +#...........#.........A...........#A........#...........A#........++threescore      *#      :     A  :    *# :        : #     : A#     :       *#       |  -20 A+............**....A#A..............*#...A#...............A#**#A..++40      |       :      A#:  *#   :        :  A#A#A*        :       : AA *   |      |       :       #A#A     :        :  *    :        :       :        |  -40 ++...............*.*...............................................++20      |       :        :       :    $   :  $    :        : $     $ $$     |  -60 B+$-$--$-B--B-$$-B-B--BB-$-B-BB-B---$B-$-$$-$-$-BB-$-B---$-B-BB-B--++0      $ B BB B:$ $$ BB $ $B $  B   $    B B  B BB B B $$ B  B $B :    $   |      +    $  +  B     +  $    +        + $     +        +    B  +        +  -80 ++------+--$-----+-------+--------+-------+--------+----$--+-------++-twenty      0       5       x      fifteen       20      25       30      35       twoscore                                    Time (s)      

hamricktruits98.blogspot.com

Source: https://www.cs.hmc.edu/~vrable/gnuplot/using-gnuplot.html

0 Response to "gnuplot draw 3d curve from function"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel