Plotting points in python - python

I want to plot some (x,y) points on the same graph and I don't need any special features at all short of support for polar coordinates which would be nice but not necessary. It's mostly for visualizing my data. Is there a simple way to do this? Matplotlib seems like way more than I need right now. Are there any more basic modules available? What do You recommend?

Go with matplotlib Chance is that sometime in the future you might need to do more than just "simple" stuff and then you don't need to invest time learning a new plot-tool.
See this link for list of plotting tools for python...

Absolutely. Matplotlib is the way to go.
The pyplot module provides a nice interface to get simple plots up and running fast, especially if you are familiar with MatLab's plotting environment. Here is a simple example using pyplot:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x_points = xrange(0,9)
y_points = xrange(0,9)
p = ax.plot(x_points, y_points, 'b')
ax.set_xlabel('x-points')
ax.set_ylabel('y-points')
ax.set_title('Simple XY point plot')
fig.show()

import matplotlib.pyplot as plt
x = range(1,10)
y = range(1,10)
plt.plot(x,y,'o')
plt.show()
Here's a simple line with made up x, y. Note: x and y are lists.
Their lengths should be equal or you'll get a error. Cheers!

I suggest the most good looking plotting library for Python: CairoPlot

You can use the Tkinter canvas widget. It uses rectangular coordinates but of course you can translate to polar. The canvas is pretty much just like it sounds -- a blank canvas on which you can draw points, lines, circles, rectangles, etc.

You could always write a plotting function that uses the turtle module from the standard library.

MathGL is GPL plotting library which have Python interface, arbitrary (including polar) curved coordinates, a lot of plot types, export to PNG, EPS, SVG, widgets, and so on. For 1D plot samples see here.

Have you tried to use pillow?
from PIL import Image, ImageDraw
#Set up canvas
img = Image.new (mode, size)
draw = ImageDraw.Draw (img)
#Draw your points
draw.point (xy, colour)

Related

Using Mayavi to make 3D graphs, with Matplotlib-style axes

I've been messing around with Mayavi for 3D graphing, and I can graph the scatter plot I want but can't seem to get the Axes to look proper. I found the following previous question that starts to get at what I'm after, but doesn't go into detail. I want a 3D scatter plot like #1 but with nice-looking axes like #2 (I'd embed but I don't have enough reputation).
The regular Mayavi Axes aren't going to cut it. Any tips for getting the planes that Matplotlib has?
This is actually pretty straightforward once we get the "trick", and I have done it many times.
The 'trick' is to generate the mayavi plot first, then transfer it into the matplotlib window where you can use all the familiar matplotlib tools to make axes with numbers, dates, arrows, or the other pieces that matplotlib provides. In this code example I'll just drop the mayavi 'copper spheres' example into a matplotlib set of axes:
import numpy, pylab, mayavi, mayavi.mlab
import matplotlib.pyplot as plt
t = numpy.linspace(0, 4 * numpy.pi, 20)
cos,sin = numpy.cos, numpy.sin
x = sin(2 * t)
y = cos(t)
z = cos(2 * t)
s = 2 + sin(t)
mayavi.mlab.points3d(x, y, z, s, colormap="copper", scale_factor=.25)
arr = mayavi.mlab.screenshot()
fig = plt.figure(figsize=(5, 5))
pylab.imshow(arr)
plt.show()
The result is just the mayavi plot in a matplotlib set of axes:
The only tricky part is that you'll need to build a working knowledge of the scales and dimensions of mayavi and matplotlib to get the two to scale together if you want to produce more than one or two manually built plots. That is non-trivial but fairly well documented for both Mayavi and Matplotlib and from the sounds of things you know both so I won't belabor those points. (Now that things are in Matplotlib you can make them part of generated PDFs too or port them into Microsoft Word with python-docx)

Changing center of rotation in a Matplotlib 3D plot

I have a 3D line plot in matplotlib, created using the following code:
def view(self):
from mpl_toolkits.mplot3d import Axes3D #noqa
import matplotlib.pyplot as plt
ax = plt.figure().gca(projection='3d')
history = np.array(self.position_history)
x, y ,z = history[:, 0], history[:, 1], history[:, 2]
ax.plot(x, y, z)
plt.show()
Here history is an Mx3 array of points. This works fine and pops up a plot as expected. I am able to click and drag to modify the azimuth and elevation interactively. I am able to zoom by right-clicking and dragging.
However I am wondering if it is possible to modify the center point of the pan and zoom? I would like to zoom into the top-right, and then pan around with the top right as my center of rotation. If you have ever used solidworks or another CAD program, this is the behavior I am after. Is this doable? If not interactively, can I do it programmatically?
And finally, if none of this is possible in matplotlib, is there another library that can accomplish what I want?
I have also run into trouble in the past in terms of customizing mplot3d, rather unsuccessfully..
And finally, if none of this is possible in matplotlib, is there another library that can accomplish what I want?
you can do this with mayavi
here is a relevant stackoverflow answer for customizing how you interact with your plot
there are also various useful tips and tricks for animating in general and for using mayavi
(apologies if this isn't useful)
Not sure this will do what you need but you can define the center when you first plot. Here, "c_x" is the center of rotation on the x axis and the -/+ 200 defines the axis to be 200 units in both direction. Likewise for y and z.
If you had the user choose the center before plotting, that could work as a crude work around.
http://matplotlib.org/api/axes_api.html?highlight=set_xbound#matplotlib.axes.Axes.set_xbound
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.autoscale(enable=False,axis='both') #you will need this line to change the Z-axis
ax.set_xbound(c_x-200, c_x+200)
ax.set_ybound(c_y-200, c_y+200)
ax.set_zbound(c_z-200, c_z+200)

Sloppy SVG generated by matplotlib resulting on poor clipping of datapoint drawing in figures

Figures that I create with matplotlib do not properly clip points to the figure axes when rendered, but instead draw additional points, even though such figures look fine in some viewers.
For example (following an example from the documentation) using
import matplotlib
matplotlib.use('SVG')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
fig = plt.figure()
ax = fig.add_subplot(111)
x, y = 12*np.random.rand(2, 1000)
ax.set(xlim=[2,10])
ax.plot(x, y, 'go') # plot some data in data coordinates
circ = patches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes,
facecolor='yellow', alpha=0.5)
ax.add_patch(circ)
plt.savefig()
I seem, when viewed for example in OS X Preview, to get
but when I view it in other editors, such as iDraw I get a mess (where, weirdly, there is a combination of correct clipping of edge points, failed clipping of points outside the axes, and clipping of the canvass at a point that does not correspond to either the axes or the range of data):
I'm not experienced with SVG, but those I've asked tell me that
I looked at the SVG file and didn't like what I saw. Characters are
flattened, and definition sections are scattered throughout the file
instead of being at the top; some defs are inside graphics constructs.
There's a lot of cruft. It turns out the definition of the clip-path
is at the very end of the svg file -- after all the uses ...
How can I get matplotlob to generate SVG that does not have these issues? I know that I can edit the SVG, but I have no idea how, and doing so defeats the purpose and I hope that it is not necessary to add a "by hand" step to my workflow.
I'm interested in understanding what the cause of the sloppy SVG generated by matplotlib is: whether it's something that can be avoided by coding a bit differently (though not, clearly, by simply checking whether every data point is in range), or whether it's a bug in matplotlib (or perhaps whether it's just a problem with ambiguities in the SVG standard). The goal is getting matplotlob to generate SVG that is not buggy.
This is probably related to a know issue and also comes up in pdfs (matplotlib data accessible outside of xlim range)
See Issues #2488 and #2423 (the later which includes a proposed fix for pdf). It is milestoned for 1.4.

matplotlib: plot a histogram from data

I have data (a spectrum) that I want to plot as a histogram.
I import the data and spectrum.shape shows me (1024,) as the format,
however plt.hist does not plot the data correctly.
If I use plt.bar(...) it works just fine, but for aesthetic reasons (I want to use the "stepfilled" histogram design) and I have to employ plt.hist which offers this option.
I really don't know what to do.
Here is my code:
import matplotlib.pyplot as plt
import numpy as np
spectrum = np.loadtxt('3000.mp', skiprows=53)
y1=spectrum[:]
num_bins = 1024
diagram = plt.hist(y1, num_bins, alpha=0.5)
plt.xlabel("TOF / $\mu$s")
plt.ylabel("# ions")
plt.show()
I hope for your help.
I am interested also in this answer. Would you share how did you get the stepfilled design with bars?
Myself I am looking for something like this:
(this image comes from http://astroplotlib.stsci.edu/page_histograms.htm)
But I do not manage to generate it easily with a spectrum as an input.

Is plotting an image on a map with matplotlib possible?

Using basemap it's easy to plot a set of coordinates, like so:
x, y = m(lons, lats)
m.plot(x, y, 'go')
but would it be possible to use an image instead of the green circle ('go')? I didn't find a direct way of doing this from the documentation.
So, let's clarify this a bit: I'm using a map generated with basemap as a background and would like to plot some .png images on top of it instead of the regular plain markers.
If you want to draw .png images then you should try http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.imshow
You might also be interested in the Matplotlib Basemap toolkit. http://matplotlib.sourceforge.net/basemap/doc/html/
For your reference, I answered a similar question to this the other day: Python Matplotlib Basemap overlay small image on map plot

Categories