How to fix matplotlib overlapping graphs [duplicate] - python

I am trying to use a forloop to produce figures for each set of data I have, but while the .show() command produces the correct figure, .savefig() keeps adding the previous plotted values to the new figure.
In my forloop, this is the relevant sample of the code.
import matplotlib.pyplot as plt
plt.plot(X,Y[:,0],'o-')
plt.xlabel('x')
plt.savefig('plot'+str(i)+'.png')
As a comparison, here is the savefig plot and here is that shown by show(). As can be seen, the savefig() plot also plotted the previous result.

You have to close current figure after saving with function
plt.close(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.close
Or you have to clean current figure after saving by plt.clf(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.clf

I made some beautiful charts before I included plt.clf() to clear the plot each time through the loop.
scatterplot1
scatterplot2
In other words, my previous plots were being added to a single figure as shown in the lots above, within my for loop as well. adding [plt.clf()] to clear the plot each time through the loop fixed this problem being clearing the figure before starting the loop iteration at the top to create a new figure with new plots.
TLDR; I included plt.clf() to clear the plot each time through the loop.

Related

How to plot two different graphs on a single figure in pandas?

I am trying to get two different plots as one plot. I will not write down my entire code (is so long), but based on the two small codes below, i get two different time series and I want to put these together in one figure.
My code for the first plot:
plt.figure(figsize=(15,4))
i = plt.plot(july/july.mean(),label='G')
my code for my second plot:
spi3 = pd.read_csv('SPI3.csv',header=0,parse_dates=True)
spi3.plot(y='spi',figsize=(16,4))
Quick dirty fix would be to plot dictionaries at first, only then plot with plt.plot. Also, if you want to plot in the same figure, define figsize only in the first figure you are plotting. (Therefore plt.figure is ommitted completely.)
spi3.plot(y='spi',figsize=(16,4))
plt.plot(july/july.mean(),label='G')

matplotlib legend performance issue

I am using Jupyter-notebook with python 3.6.2 and matplotlib to plot some data.
When I plot my data, I want to add a legend to the plot (basically to know which line is which)
However calling plt.legend takes a lot of time (almost as much as the plot itself, which to my understanding should just be instant).
Minimal toy problem that reproduces the issue:
import numpy as np
import matplotlib.pyplot as plt
# Toy useless data (one milion x 4)
my_data = np.random.rand(1000000,4)
plt.plot(my_data)
#plt.legend(['A','C','G','T'])
plt.show()
The data here is just random and useless, but it reproduces my problem:
If I uncomment the plt.legend line, the run takes almost double the time
Why? Shouldn't the legend just look at the plot, see that 4 plots have been made, and draw a box assigning each color to the corresponding string?
Why is a simple legend taking so much time?
Am I missing something?
Replicating the answer by #bnaecker, such that this question is answered:
By default, the legend will be placed in the "best" location, which requires computing how many points from each line are inside a potential legend box. If there are many points, this can take a while. Drawing is much faster when specifying a location other than "best", e.g. plt.legend(loc=3).

time lapse graphs matplotlib

I'm trying to create a matplotlib graph that shows how to a certain data set changes over time. What I've been trying to do is create a plot and show it, pause for one second, clear the plot, and then show the next one in the array. I've gotten pretty close with the code below, but sadly it just crashes as is.
for expo in sorted_data:
plt.plot(expo["x"], expo["y"])
plt.show(block=False)
time.sleep(1)
plt.gcf().clear()
sorted_data contains the data sorted by when the data was collected.
Use matplotlib.animation. You can find many examples here: http://matplotlib.org/examples/animation/index.html

Show new matplotlib graph further down Jupyter notebook

I'm learning Matplotlib and using a Jupyter notebook to track each thing that I learn. However, I ran into a problem because I have multiple cells with matplotlib code. In one of my first cells, I run plt.show(), which outputs a plot beneath the cell. Further down the page, I have some other code which plots new points, resizes an axis, etc., then runs plt.show()....which works, but applies the changes to the original plot that was created after the first cell.
Is there any way to get a new plot window to display beneath whichever cell I am running?
(The reason I want to do this: The first cell might be an example showing how to plot a basic set of points. I want this to display its own simple plot. Further down the page, I resize axes and change the style of graph. However, when this plots, I want to see a separate plot, or maybe the same plot redone (as in, it can keep the original points I plotted -- no need to clear the whole thing) but with the new changes, beneath this more complex cell.)
UPDATE: Images.
In Image 1, I have run the first cell of code. The graph displays beneath the cell. Just as I want.
In this second image, I've now run the lower block of code (marked [3]). The changes, however, are applied to the plot sitting above it, because that's where it was originally created. But I'd like a new plot, or maybe not a clean new plot, but at least some way to make that plot display beneath cell [3] that I just ran.
In the comments, you mentioned that you're using the %matplotlib notebook magic, because it allows interactivity.
One option is to stop using interactivity.
As you found, you can turn off interactivity with plt.ioff(). You could also stop using %matplotlib notebook altogether and instead use %matplotlib inline (called at the top of the notebook). With %matplotlib inline, you don't need to call plt.show().
But you want to use interactivity.
So what you should do is define a new figure after you've plotted your first figure. To do this, call plt.figure() after the first plot, before the code for the second.

savefig loop adds previous plots to figure

I am trying to use a forloop to produce figures for each set of data I have, but while the .show() command produces the correct figure, .savefig() keeps adding the previous plotted values to the new figure.
In my forloop, this is the relevant sample of the code.
import matplotlib.pyplot as plt
plt.plot(X,Y[:,0],'o-')
plt.xlabel('x')
plt.savefig('plot'+str(i)+'.png')
As a comparison, here is the savefig plot and here is that shown by show(). As can be seen, the savefig() plot also plotted the previous result.
You have to close current figure after saving with function
plt.close(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.close
Or you have to clean current figure after saving by plt.clf(): http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.clf
I made some beautiful charts before I included plt.clf() to clear the plot each time through the loop.
scatterplot1
scatterplot2
In other words, my previous plots were being added to a single figure as shown in the lots above, within my for loop as well. adding [plt.clf()] to clear the plot each time through the loop fixed this problem being clearing the figure before starting the loop iteration at the top to create a new figure with new plots.
TLDR; I included plt.clf() to clear the plot each time through the loop.

Categories