Save images of a matplotlib figure at different coordinates? - python

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.

Related

How to make plots customizable in python

I have two issues with my python plot that would be grateful if anyone could help me with:
1- I wonder if it is possible in python to have the option for the plots after display to add horizontal or vertical lines, so that these new lines could be added, moved or deleted without the need to run the code again.
to say it more clearly, I am looking for additional features that adding them does not need to change the code and they only enable me to manually draw on the already plotted image.
2- I want to plot a very large image in the real size, So that I need to add the horizontal and vertical slide bars to be able to scroll up/down or left/right in the plot?
I need to combine these two ability for my project, can someone help me with that?
1- You can't physically draw on it, but you can make a plot in matplotlib interactive as follows:
import matplotlib.pyplot as plt
plt.ion() # turns on interactive mode
fig = plt.figure()
ax = fig.add_subplot()
plt.ylim(-10, 10)
plt.xlim(0, 10)
while True:
plt.axhline(float(input("number")))
fig.canvas.draw()
fig.canvas.flush_events() # draws
This program allows you to create horizontal lines based on user input.
I think you can solve 2 with tkinter, but that would be pretty difficult. There might also an easier way. See this stack overflow question for an example of an interactive plot in tkinter. I believe this plot can be made bigger and scrollable, but I am not sure.

How to send multiple plots generated by matplotlib to a pptx without any overlapping?

I am working on a project where I am generating hundreds of plots using the matplotlib module in Python. I want to put these plots in a pptx using the python-pptx module, let's say four plots on a slide without storing these plots on the local disk.
To overcome the storing problem I am using the BytesIO python module, which stores the plots inside the buffer, and then send these plots to the pptx.
The major issue that I am facing is the overlapping of the plots.
Question is how to send these plots serially to pptx so that we can avoid the overlapping?
Screenshot of pptx generated
I have added a screenshot of the pptx, where I am trying to add the two plots
Plot 1 (Age vs Name),
Plot 2 (Height vs Name),
but if you see the Plot 2 the data of plot 1 and plot 2 are getting overlapped. I want to avoid this overlapping.
You need to clear the axes between each plot, there are several ways to do that:
plt.clf(): clears the current figure
plt.cla(): clears the current axes
So instead of e.g.
plt.scatter(x, y1)
# save first plot
plt.scatter(x, y2)
# save second plot
You do
plt.scatter(x, y1)
# save first plot
plt.clf()
plt.scatter(x, y2)
# save second plot
And the two scatter plots will be drawn separately. This is probably the most 'blunt' way to approach this, but it should work fairly well. It is by no means the best way to do it for any specific case.
The figure is also cleared when plt.show() is called - but I expect that is undesirable in this case.

Do I need a figure? What are they for?

I have begun using matplotlib and I am somewhat confused as to why figures exist. Sometimes I see code where a figure is declared and then a plot is made, and sometimes I see things like this:
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('initial.dat','float')
plt.plot(data[:,0], data[:,1])
plt.xlabel("x (Angstroms)")
plt.ylabel("V (eV)")
plt.savefig('v.png',bbox_inches='tight')
plt.clf()
I read the documentation on figure and plot, but I don't get it. Why do figures exist?
A figure will always exist once you create some plot with matplotlib.
The introductory matplotlib page may help here:
The whole figure. The figure keeps track of all the child Axes, a smattering of ‘special’ artists (titles, figure legends, etc), and the canvas. (Don’t worry too much about the canvas, it is crucial as it is the object that actually does the drawing to get you your plot, but as the user it is more-or-less invisible to you). A figure can have any number of Axes, but to be useful should have at least one.
You can imagine the figure to be the white sheet of paper you draw a plot on. A figure has some size, maybe a background and most importantly it is the container for everything you draw into it. In most cases this will be one or more axes. If there wasn't any figure, there wouldn't be any sheet of paper to draw your plot to (you cannot draw a line in the air).
Even if you haven't explicitely created the figure, it is automatically created in the background.
import matplotlib.pyplot as plt
plt.plot([1,2,3])
# at this point we already have a figure, because the plot needs to live somewhere
# we can get a handle to the figure via
figure = plt.gcf()
Examples of when you explicitely need a figure:
If you want to create a second figure.
plt.plot([1,2,3])
plt.figure(2)
plt.plot([2,4,6])
If you want to set the figure size or other figure parameters.
plt.figure(figsize=(5,4), dpi=72)
If you want to change the padding of the subplot(s).
fig, ax=plt.subplots()
fig.subplots_adjust(bottom=0.2)

matplotlib: enlarge axis-scale label

Is there a way to enlarge the axis-scale label in matplotlib (circled in red in the enlarged plot below)?
I've used ax.tick_params() to successfully edit the tick labels, but I haven't been able to find anything about this specific piece of the plot.
Worse comes to worst, I could go with a manual text() insertion, but I'd like something more direct if possible.
Add a line like this
ax.xaxis.get_children()[1].set_size(15)
To change your major tick scale label (I guess we can call it so) to 15 points, if you plot the plot on ax.
If you plot using the pyplot API, add a line of ax=plt.gca() as well.

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.

Categories