How To Use Gnuplot To Graph Data On The Raspberry Pi

I was recently testing a sensor which needed calibrating. This involved plotting some data and making some adjustments based on the resulting graph. As a Windows user this is a task I would normally perform in Microsoft Excel or LibreOffice Calc.

In this case I decided to try to do it on the Pi given I was already working wthin the LXDE environment. Could I do some simple plots without getting frustrated with tons of obscure command line syntax?

Example gnuplot GraphThe answer was yes and came in the form of “gnuplot”, a command-line driven graphing utility. It’s got a lot of options but it only takes five minutes to master the basics.

This tutorial just scratches the surface but aims to provide a quick reference for creating graphs from simple datasets.

Install gnuplot

To install gnuplot on the Raspberry Pi use the following command :

sudo apt-get install gnuplot-x11

You may have to answer “Y” if prompted.

Generate Some Example Data

In order to do the example plots I needed some test data. Here is a simple Python script to create some test data. It creates a plain text file called “mydata.dat”. Each line contains a set of data points where each number is separated with a space character.

#!/usr/bin/python
import math
f = open('mydata.dat', 'w')
# Loop
for degrees in range(720):
  # Generate three data points
  si = math.sin(math.radians(degrees))
  co = 0.5 * math.cos(math.radians(degrees))
  if si>0:
    sq = 0.6
  else:
    sq = -0.6
  # Write 3 data points to text file
  data = "{} {} {} {}\n".format(degrees,si,co,sq)
  f.write(data)
f.close()

You can download this script directly to your Pi using :

wget https://bitbucket.org/MattHawkinsUK/rpispy-misc/raw/master/gnuplot/gnuplot_generate_data.py

Run it using :

sudo python gnuplot_generate_data.py

The script will create “mydata.dat” and the contents will look a bit like this :

0 0.00 0.50 -0.60
1 0.02 0.50 0.60
2 0.03 0.50 0.60
3 0.05 0.50 0.60
4 0.07 0.50 0.60
5 0.09 0.50 0.60
6 0.10 0.50 0.60
7 0.12 0.50 0.60
8 0.14 0.50 0.60
9 0.16 0.49 0.60
10 0.17 0.49 0.60
....

The first column is just a number sequence. The other three columns are our data. If you were plotting temperature you may only have 1 column of data. I used three for this tutorial to make the example plots a bit more interesting.

Plot The Data

If you haven’t already launch the graphical environment by typing :

startx

You can launch gnuplot by either typing “gnuplot” in a terminal window or using the shortcut under XXXXXX. You will be presented with a command prompt awaiting your instructions.

To plot data you can enter :

plot "mydata.dat"

This only plots the data from the 2nd column. To plot the two other sets you can type :

plot "mydata.dat" using 1:2, "mydata.dat" using 1:3, "mydata.dat" using 1:4

This tells gnuplot to plot three sets of data using columns 2, 3 and 4.

Example gnuplot Graph

Many of the customisations you can make to your graph are either made by adding parameters to the “plot” command or issuing “set” commands.

Setting a Plot Title and Axis Labels

To change the plot title you can type the following command :

set title "Example Plot"

To change the data labels you can modify your plot command :

plot "mydata.dat" using 1:2 title "Sin", "mydata.dat" using 1:3 title "Cos"

This can be abbreviated to :

plot "mydata.dat" u 1:2 t "Sin", "mydata.dat" u 1:3 t "Cos"

To change the axis labels you can use the following commands :

set xlabel "Minutes (mins)"
set ylabel "Temperature (degrees)"

Example gnuplot Graph

Lines and Points

You can also change the way the data points are represented on the graph. By default points are used. You can change the style to “lines” or “linespoints” using the “with” keyword :

plot "mydata.dat" u 1:2 t "Sin", "mydata.dat" u 1:3 t "Cos" with lines

This makes the square wave look nicer.

Example gnuplot Graph

 Colours

It’s easy to change the colour of your data. Just use the “lt” paramenter :

plot "mydata.dat" using 1:2 lt rgb "blue", "mydata.dat" using 1:3 lt rgb "violet"

Example gnuplot Graph

You can use a range of colours including black, red, green, blue, magenta, cyan, brown and light red.

Customising the Axis Scale

By default the axis will autoscale. Most of the time this is fine but you may want to tweak the axis values to make it look a bit nicer. You can either use :

set yrange [-1.5:-1.5]

or modify your plot command :

plot [] [-1.5:1.5] "mydata.dat" u 1:2 t "Sine", "mydata.dat" u 1:3 t "Cosine"

In our example we modified the y-axis and this would give us a plot like this :

Example gnuplot Graph

You can reset the axis auto-scaling with “set autoscale”.

Here is a final example :

plot [] [-1.5:1.5] "mydata.dat" u 1:2 t "Sine" with lines lw 2, "mydata.dat" u 1:3 t "Cosine" with lines lw 2, "mydata.dat" u 1:4 t "Square" with lines lw 2

In this final example I’ve changed the data to use “lines” and added a”lw” parameter to increase the line width to 2. Modifying the y-axis has also ensured the key doesn’t clash with the data lines :

Example gnuplot Graph

Other Tips

When you’ve changed settings using the “set” commands you can quickly re-draw your graph using “replot” rather than using the complete plot command. Don’t forget to use the up and down arrow keys to recall previous commands. That saves a lot of typing!

gnuplot can do lots, lots more but hopefully the information here is enough to get you started.

This entry was posted in Software, Tutorials & Help and tagged . Bookmark the permalink.


5 Responses to How To Use Gnuplot To Graph Data On The Raspberry Pi

  1. Paul Adomshick says:

    Outstanding. This is precisely what I’ve wanted, but just haven’t gotten around to researching. I’ve been prototyping a RasPi-based combined weather station and HVAC monitoring station for my home, and wanted to work on an automated graphing solution. This looks like the basis on which I’ll be adding that to the project. In all likelihood, I’ll be writing python scripts to standardize the formatting of the data I’m generating. After reading some of gnuplot’s FAQ, it appears that the output format options are outstanding and provide quite a bit of flexibility, so I should be able to easily create a script that uploads the resulting graphs to a website automatically via FTP.

    Thanks for covering this topic.

    • Matt says:

      Glad it was useful. The other thing that is great with gnuplot is that you can create a script file with all the “set” commands in it so you can create a plot in one go. You can also get it to create PNG files. In fact I used that feature to create the images in this post … although I cheated and used a laptop for that!

  2. cm2 says:

    Since you are already using Python to generate data, you may be interested in using powerful Python plotting modules. My favorite is matplotlib. I’ve seen pages where people have gotten matplotlib up and running on a Pi, but I’ve not done it yet myself.

  3. Fernando says:

    Nice post!
    How can I plot data obtained from a C (or Python) code? I mean, I have a code that generates some data, and I’d like to plot it! (as part of the program, of course)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>