Overlay transparent paths in matplotlib? - python

from pylab import *
plot(randn(1000), randn(1000), alpha=0.1)
[<matplotlib.lines.Line2D at 0x7f756e65a450>]
savefig('test.png')
gives this:
Where the paths are combined, and then the transparency is applied after. I want something like this:
This was post-edited in inkscape to break up the paths and then overlay them. This isn't practical with the data set I'm using, because it's too large, and basically crashes my computer when I try to open it in inkscape. Is there any way to do this in matplotlib itself?
Edit: the actual data I'm using a single long vector of geophysical data, and I'm trying to plot a phase portrait with plot(vec[:-1], vec[1:]).

You could just use a loop to create the plot:
for i in range(100):
plot(randn(10), randn(10), alpha=0.5, c='b')
will give you something similar (the transparency is "added" for every iteration of the loop):
Depending on your data set, however, I don't know how practical this approach would be.

Related

Name of this 'horizontal section' diagram and how to implement in PyPlot

I need to create a plot with matplotlib/pyplot in a very specific way. I want the curve to never go up again, instead I want these horizontal sections with the little overstanding line, like shown in the picture:
Source: https://scikit-learn.org/stable/auto_examples/model_selection/plot_precision_recall.html#sphx-glr-auto-examples-model-selection-plot-precision-recall-py
My problem is I don't know how this type of line-style is even called so I don't know what to search for. It is often used for PR-Curves in deep learning.
Does anyone know how this is called and maybe also how to plot a graph in this style with pyplot?
This is my current approach by just plotting with the plot function. As you can see there are these rising edges which I want to get rid of.
plt.plot(x, y, linewidth=3)
The example you cited from scikit-learn uses drawstyle='steps-post' (this demo illustrates what it does), so try
plt.plot(x, y, drawstyle='steps-post')

Save images of a matplotlib figure at different coordinates?

I want to create a big figure using matplotlib, and then save a few parts of it at different specific coordinates (so manual zooming after plt.show() is not an option - there is no guarantee I can zoom to some precise coordinates - or is there?). The picture is fairly large, so I don't want to generate it all over again and again, specifying xlim and ylim every time before plotting. Is there any way to change axes limits after the figure is created? And I am not using an ipython console, but I need to use it in a script.
There is no problem with using xlim and ylim here. Take the following example:
import matplotlib.pyplot as plt
plt.plot(range(20))
plt.savefig("1.png")
plt.xlim(0,10)
plt.savefig("2.png")
plt.xlim(0,30)
plt.savefig("3.png")
Here a diagonal line is plotted, then we zoom into the first half of the line, then we zoom back out. At each stage a new png file is created. There is no need for redrawing here.

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.

Change dynamically the contents of a matplotlib plot

I while ago, I was comparing the output of two functions using python and matplotlib. The result was as good as simple, since plotting with matplotlib is quite easy: I just plotted two arrays with different markers. Piece of cake.
Now I find myself with the same problem, but now I have a lot of pair of curves to compare. I initially tried plotting everything with different colors and markers. This did not satisfy me since the ranges of each curve are not quite the same. In addition to this, I quickly ran out of colors and markers that were sufficiently different to identify (RGBCMYK, after that, custom colors resemble any of the previous ones).
I also tried subplotting each pair of curves, obtaining a window with many plots. Too crowded.
I tried one window per plot, too many windows.
So I was just wondering if there is any existing widget or if you have any suggestion (or a different idea) to accomplish this:
I want to see a pair of curves and then select easily the next one, with a slidebar, button, mouse scroll, or any other widget or event. By changing curves, the previous one should disappear, the legend should change and its axis as well.
Well I managed to do it with an event handler for mouse clicks. I will change it for something more useful, but I post my solution anyway.
import matplotlib.pyplot as plt
figure = plt.figure()
# plotting
plt.plot([1,2,3],[10,20,30],'bo-')
plt.grid()
plt.legend()
def on_press(event):
print 'you pressed', event.button, event.xdata, event.ydata
event.canvas.figure.clear()
# select new curves to plot, in this example [1,2,3] [0,0,0]
event.canvas.figure.gca().plot([1,2,3],[0,0,0], 'ro-')
event.canvas.figure.gca().grid()
event.canvas.figure.gca().legend()
event.canvas.draw()
figure.canvas.mpl_connect('button_press_event', on_press)
Sounds like you want to embed matplotlib in an application. There are some resources available for that:
user interface examples
Embedding in WX
I really like using traits. If you follow the tutorial Writing a graphical application for scientific programming , you should be able to do what you want. The tutorial shows how to interact with a matplotlib graph using graphical user interface.

Python plotting: How can I make matplotlib.pyplot stop forcing the style of my markers?

I am trying to plot a bunch of data points (many thousands) in Python using matplotlib so I need each marker to be very small and precise. How do I get the smallest most simple marker possible? I use this command to plot my data:
matplotlib.pyplot( x , y ,'.',markersize=0.1,linewidth=None,markerfacecolor='black')
Then I can look at it either with pl.show() and then save it. Or directly use plt.savefig('filename.ps') in the code to save it. The problem is this: when I use pl.show() to view the file in the GUI it looks great with small tiny black marks, however when I save from the show() GUI to a file or use directly savefig and then view the ps I created it looks different! Each marker has gained a little blue halo around it (as if it started at each point to connect them with the default blue lines, but did not) and the style is all wrong. Why does it change the style when saved? How do I stop python from forcing the style of the markers? And yes I have looked at some alternative packages like CairoPlot, but I want to keep using matplotlib for now.
Update: It turns out that the save to PNG first makes the colors turn out okay, but it forces a conversion of the image when I want to save it again as a .ps later (for inclusion in a PDF) and then I lose quality. How do I preserve the vector nature of the file and get the right formatting?
For nice-looking vectorized output, don't use the '.' marker style. Use e.g. 'o' (circle) or 's' (square) (see help(plot) for the options) and set the markersize keyword argument to something suitably small, e.g.:
plot(x, y, 'ko', markersize=2)
savefig('foo.ps')
That '.' (point) produces less nice results could be construed as a bug in matplotlib, but then, what should "point" mean in a vector graphic format?
Have you tried the ',' point shape? It creates "pixels" (small dots, instead of shapes).
You can play with the markersize option as well, with this shape?
If you haven't, you should try saving in a rasterizing engine -- save it to a PNG file and see if that fixes it. If you need a vector plot, try saving to PDF and converting with an external utility. I've also had problems before with the PS engine that were resolved by saving with the Agg or PDF engines and converting externally.

Categories