Short guide how to use gnuplot with python? - python

I'm trying to draw a graph in Python, using Gnuplot. I have a hard time finding any guide/tutorials how to start.
What I'm wondering: what files/programs are necessary?(I'm using Ubuntu), Where do I begin?
If anyone could recommend a good tutorial, that would be very appreciated!
Thank you!

You could try gnuplot.py. It is an interface to gnuplot I used in the past.
In the website you have some indications and there are some example scripts in the distribution.
In fact it is very easy to run directly gnuplot from python. The gnuplot.py source code will give you valuable hints. See also here and here for other alternatives.
As other recommends the alternative is to use matplotlib. Matplotlib is great and I use it as my main visualization library. The downside is that working with a high number of data it can become slow. gnuplot in this case is a good option.

Your approach depends on what you already have and what you want to work with. To plot a graph with gnuplot you need two things:
A gnuplot script, that describes how the resulting plot should look like (title, axis description, legend...)
A data file, which holds the data you want to plot
If you already have lets say the gnuplot script file and you simply want to write new data files using python, than this approach is sound in my option. Simply export data to the specified format you used in your data files before and run gnuplot from within python with something like
import os
import subprocess
p = subprocess.Popen("gnuplot <scriptname>", shell = True)
os.waitpid(p.pid, 0)
Don't forget that you maybe have to change the path the data file in your gnuplot script if you write out new data files. So something like this:
plot "<path>" ...
If you don't yet have a gnuplot script you want to use you can definitely write one and use that from this point on, but using python there are also other alternatives.
You could take a look at matplotlib which is a plotting library that is very similar in the way Matlab uses the plot command. It is very well documented and there are lots of tutorials and examples online you can learn from and work with.

As a gnuplot fan, I use this gnuplot wrapper https://github.com/mzechmeister/python/wiki/gplot.py.
Here is a demo snippet
from gplot import *
gplot.term('wxt')
gplot.title('"gplot.py"').grid()
gplot.xlabel('"time"')
gplot([1,2,0,4,3.5], 'w l, sin(x), "<seq 10" us 1:(cos($1))')

about 10 years later, let me point the attention to autogpy or Autognuplotpy.
Autogpy aims at a full generation of gnuplot scripts (and suitably dumped data) from python.
For instance, the python code
import autogpy
import numpy as np
xx = np.linspace(0,6,100)
yy = np.sin(xx)
zz = np.cos(xx)
with autogpy.AutogpyFigure("test_figure") as figure:
# gnuplot-like syntax
figure.plot(r'with lines t "sin"',xx,yy)
# matplotlib-like syntax
figure.plot(xx,zz,u='1:2',w='lines',label='cos')
generates the gnuplot script
set terminal epslatex size 9.9cm,8.cm color colortext standalone 'phv,12 ' linewidth 2
set output 'fig.latex.nice/plot_out.tex'
p "fig__0__.dat" with lines t "sin",\
"fig__1__.dat" u 1:2 with lines t "cos"
and dumps readable data.
Supports latex, tiks and png terminal, but can be easily expanded to more.
Disclaimer: I am the author.

Related

How to get a plot out of LuxPy package

I'd like to plot the color-rendering information for a given spectrum using the lx.cri.plot_cri_graphics(SPD) function of the LuxPy package.
There is the following example code on page 17 of this official tutorial which passes a predefined spectrum (SPD) to the mentioned function.
"The LuxPy.cri subpackage also supports a function that
[...] provides TM30-like graphical output. For example, the code below generates the output in Fig. 7"
import luxpy as lx
SPD = lx._CIE_ILLUMINANTS['F4']
data,_,_ = lx.cri.plot_cri_graphics(SPD)
Figure 7:
In my case, the program just finishes without plot, errors or terminal output.
The data object in the above example contains a bunch of data and is of type dict, but no plot appears and the script just finishes. Many of the package's classes have dedicated .plot() member functions, which - for my understanding - should all work the same way. But I do not get any plots popping up for any of those either (like I'm used to from working with Matplotlib).
Is there anything I need to do beside calling the .plot_cri_graphics() funtions? Something that may be self-explanatory for someone more experienced?
Do I have to pass data to another plot funtion to actually get a plot output?
The official tutorial uses IPython with inline plotting (see section 5.1: %matplotlib inline, see Plotting for details). If you run the example as plain python file, you'll need to add plt.show() at the end to actually show the plot.

Save figure parameters after interactive tweaking

I often find myself using matplotlib to quickly display data, then later going back and tweaking my plotting code to make pretty figures. In this process, I often use the interactive plot window to adjust things like spacing, zooming, cropping, etc. While I can easily save the resulting figure to an image file, what I really want is to save the sequence of function calls/parameters that produced it.
Note that I don't particularly care to open the same figure again (as in Saving interactive Matplotlib figures). Even something as simple as being able to print the various properties of the figure and axes would be useful.
While I don't have the answer to your specific question, I'd generally suggest using the Ipython Notebook for these things (and much more!)
Make sure you have %pylab inline in one cell.
When you plot, it will display it in the notebook itself. Then within your cell, just keep experimenting until you have it right (use Ctrl-Enter in the cell). Now the cell will have all the statements you need (and no more!)
The difference between the command line interpreter and the notebook is that the former all statements you typed which leads to a lot of clutter. With the notebook you can edit the line in place.
A similar question here
has an answer I just posted here.
The gist: use MatPlotLib's picklable figure object to save the figure object to a file. See the aforementioned answer for a full example.
Here's a shortened example:
fig, ax = matplotlib.pyplot.subplots()
# plot some stuff
import pickle
pickle.dump( fig, open('SaveToFile.pickle', 'wb') )
This does indeed save all plotting tweaks, even those made by the GUI subplot-adjuster. Unpickling via pickle.load() still allows you to interact via CLI or GUI.

plot shapefile in python

I have a couple shape files that I want to plot some scatterplot data on top of that.
Does anyone have a way to load a shape file then plot it?
I've followed a couple of tutorials, but have not been successful so far.
The shape file, I am trying to use is one of the roads in Pakistan.
Found Here
I downloaded the modules pyshp and shapelib but am open to others!
Helpful tutorial for shapefiles and using basemap to plot maps: http://www.packtpub.com/article/plotting-geographical-data-using-basemap
As much as i love D3, Matplotlib and R, this sounds like you just want create an overlay above a Google Maps chart.
This is easier than you might expect:
https://developers.google.com/maps/documentation/javascript/overlays
Check out Qgis for that purpose.
It has a python console that enables you to treat data in an efficient way.
It also reads and writes .shp-files.

Minimalistic Real-Time Plotting in Python

I've been using python extensively to extract data from various external pieces of equipment (ranging from arduinos to oscilloscopes), and I'm looking for a simplistic way to plot stuff.
There's already some answers to similar questions on stack overflow:
What is the best real time plotting widget for wxPython?
With most pointing to this fine piece of code by Eli Bendersky
http://eli.thegreenplace.net/2008/08/01/matplotlib-with-wxpython-guis/
But the scope of the code is far more complicated that what I'm looking for. I'm looking for something rather minimalistic that just plots the data in real-time as it streams from a source -- it doesn't need a GUI, radio buttons, knobs and sliders, or anything like that.
It seems that solutions such as calling pylab.plot() or pylab.show() in a loop doesn't seem to give the correct behavior.
Does anyone have suggestions?
Well, this isn't a wxPython answer but I've used Chaco for this sort of thing and it's pretty straight forward. There is a nice example of a realtime spectrum analyzer that may be similar to your use case and a nice tutorial. So, if you aren't tied to wxPython for other reasons, that might be worth a look.
Besides the matplotlib examples you've found, there's also wx.lib.plot and several answers here: http://wxpython-users.1045709.n5.nabble.com/real-time-data-plots-td2344816.html
To use real time plotting you need to send signals to the GUI loop. If you use interactive mode (Ipython) then you might also like to use threads.
I have written some decorators to handle the GUI and threading in a really easy and clean way. They work for the QT backend.
https://gist.github.com/Vrekrer/106c49a3ae6d420937aa
A sample code for Ipython will look like this
#%pylab qt
#https://gist.github.com/Vrekrer/106c49a3ae6d420937aa
import QThreadDecorators
import time
#QThreadDecorators.GUI_Safe
def myplot(x,y):
#This will plot a new line for each call (ok for an example)
plot(x, y, 'bo-')
grid(True)
#QThreadDecorators.AsQThread
def myLoop(x):
y = x * nan
for i, xi in enumerate(x):
#get some data
time.sleep(1)
y[i] = xi**2
#plot in real time
myplot(x,y)
#just call the function and it will run on a thread
myLoop( arange(20) )

Interactive plotting in Python?

Matlab and Mathematica both have features that allow the user to manipulate the contents of a plot using, say, a slider. For example, if you have a set of 3D data, it is easy to make a small program that lets you view 2D slices of a set of 3D data where the user can slide a slider to move through which slice is displayed. Is there anything in python that allows for this sort of capability without tons of effort? For example, is it possible to do such a thing in matplotlib, or something similar? I
Thanks.
My first thought would be Mayavi, which is great for data visualization, especially in 3D. It relies on VTK. It is included in the Enthought flavoured version of Python, together with Chaco for 2D plotting. To get an idea, look at Travis Vaught's nice screencast in Multidimensional Data Visualization in Python - Mixing Chaco and Mayavi.
It also possible to embed basic interactive functionalities (like slider) to Matplotlib, see matplotlib.widgets and the widget examples.
Finally, you can use rpy (or better, rpy2) and benefit from the R interface.
Have you looked at Vtk? http://www.vtk.org/ One of their demos does exactly what you're asking.
In principle, you can do it by help of MathGL. This is cross-platform GPL library for plotting.
For each mouse clicks you can find the x,y,z position in plot or clicked object and adjust (replot) some other information correspondingly. However you should handle mouse clicks by yourself (for example, using PyQt).
Another option is to use python within the SAGE computation interface/environment, which has the #interact command (see here for specific help on this command)

Categories