1.This becomes the interactive plot I am referring to. You will need to open the figure that appears at the bottom of the screen (if it does not display automatically) immediately after you start the program, in order to see the "animation". My question is: how do I record all of the updates in this interactive plot as a video? I do not want to record the screen. I also do not want to replace my current code fully with an animation object. Is there any way to create a video recording this interactive plot by supplementing the interactive plotting code rather than fully replacing it?
import matplotlib.pyplot as plt
plt.ion()
plt.figure()
for i in range(1000):
plt.axis((0,10,0,100))
plt.plot([1,2,3,4,5,6,7,8,9],[i,i,i,i,i,i,i,i,i],'ro')
plt.pause(.1)
plt.cla()
plt.clf()
Related
I am making some small tests in Jupyter. The user should see two plots, one on the left and one on the right. Than after clicking somewhere on the left plot something on the right plot should happen. For example here a click on the left plot will produce a red dot on the right plot in the same place:
%matplotlib notebook
def onclick(event):
ax.clear()
ax2.clear()
ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax2.set_xlim(0,10)
ax2.set_ylim(0,10)
ax2.plot([event.xdata],[event.ydata],'o',color='red')
ax.figure.canvas.draw_idle()
ax2.figure.canvas.draw_idle()
fig = plt.figure(figsize=(20,10))
ax = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
ax.set_xlim(0,10)
ax.set_ylim(0,10)
ax2.set_xlim(0,10)
ax2.set_ylim(0,10)
cid = fig.canvas.mpl_connect('button_press_event',onclick)
This works, but the visualization in Jupyter is not the best. Is there a way to have this kind of interactive plots working outside of a Jupyter notebook ? Maybe in a window with varying dimensions ? As an example, how would one proceed with the example above ?
You can use plotly and export your plots to html file:
https://plotly.com/python/interactive-html-export/
I think I found a possible simple answer to my needs. Simply put the code in the question in a python script, remove the 'magic' command and insert at the end:
plt.show(block=True)
This way matplotlib will just use a different backend than notebook or inline in Jupiter and plot the figure in a separate window. This window is compatible with the interactive commands from matplotlib. I am not sure about widget compatibility though I will try and update the answer.
Update: I do not think ipywidgets can be used with plt.show() since these are not plotted in an axes, but there are some widgets within matplotlib (matplotlib.widgets) that can be used. Though, the resulting speed in my case is not satisfactory so I would avoid combining matplotlib widgets with matplotlib event catching.
for debugging purposes I would like to have my script show intermediate steps and not just the final plot when working with matplotlib. The problem is that after calling plt.show(), the axis is reset and drawing starts anew. Is there a way to call plt.show() and continue working with the same axis?
I am working inside PyCharm.
Code concept:
import statements
create part of plot
plt.show()
create next part of plot
plt.show() # Should show whatever was in the first plotted window plus what was added in the meantime
create final part of plot
plt.show() # Should show whatever was in the second plotted window plus what was added in the meantime
Thanks!
Edit:
System: Windows 10 running Python 3.7.1 and matplotlib 3.3.3
Your best bet to save the plot as it evolves and then compare the different saved figures.
#create part of plot
plt.savefig('first_part')
#create rest of plot
plt.savefig('second_part')
I am using the following functions in order...
- plt.figure()
- plt.plot()
- plt.ylim
- plt.xticks()
- figure = plt.gcf()
- figure.set_size_inches()
- plt.savefig()
I just want to save the figure as png, which I've been doing successfully. But the GUI keeps showing up and I am going to generate a bunch of graphs in one script, I don't want the GUI popping up every time one is created and slow my run time.
Does anyone know why it is showing up still?
If you are using a Jupyter Notebook, there are a number of potential solutions posted here.
To summarize, try this to disable inline output from Matplotlib:
import matplotlib as plt
plt.ioff()
Or put this at the start of a cell to prevent it from creating output:
%%capture
In matplotlib.pyplot, what is the difference between plt.clf() and plt.close()? Will they function the same way?
I am running a loop where at the end of each iteration I am producing a figure and saving the plot. On first couple tries the plot was retaining the old figures in every subsequent plot. I'm looking for, individual plots for each iteration without the old figures, does it matter which one I use? The calculation I'm running takes a very long time and it would be very time consuming to test it out.
plt.close() will close the figure window entirely, where plt.clf() will just clear the figure - you can still paint another plot onto it.
It sounds like, for your needs, you should be preferring plt.clf(), or better yet keep a handle on the line objects themselves (they are returned in lists by plot calls) and use .set_data on those in subsequent iterations.
I think it is worth mentioning that plt.close() releases the memory, thus is preferred when generating and saving many figures in one run.
Using plt.clf() in such case will produce a warning after 20 plots (even if they are not going to be shown by plt.show()):
More than 20 figures have been opened. Figures created through the
pyplot interface (matplotlib.pyplot.figure) are retained until
explicitly closed and may consume too much memory.
plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.
plt.close() closes a window, which will be the current window, if not specified otherwise.
There is a slight difference between the two functions.
plt.close() - It altogether plots the graph in seperate windows,releasing
memory,retaining each window for view.
plt.clf() - We can say,it displays the graph in the same window one after other
For illustration, I have plotted two graphs with paramters year and views on X axis and Y axis each. Initially I have used closed function.it displayed the graphs in two seperate windows…
Afterwords, when I run the program with clf() it clears the graph and displays next one in same window i.e figure 1.
Here is the code snippet -
import matplotlib.pyplot as plt
year = [2001,2002,2003,2004]
Views= [12000,14000,16000,18000]
Views2 = [15000,1800,24000,84000]
plt.plot(year,Views)
plt.show()
plt.clf()
plt.plot(year,Views2)
plt.show()
plt.clf()
I want to make an animated barchart in Python and save this animation in mp4 format. My problem is that the frames in the saved video overlay, although I use "blit=True" to tell the animation that only the things that change from frame to frame are drawn. Surprisingly, this problem does not occur in the built-in preview of Python.
Here is a minimal that reflects my situation:
import matplotlib.pyplot as plt
from matplotlib import animation
def barlist(n): #That's the list of bars I want to display
C=[]
for k in range(1,6):
C.append(1/float(n*k))
return C
fig=plt.figure()
n=100 #Number of frames
def animate(i):
x=range(1,6)
y=barlist(i+1)
return plt.bar(x,y)
anim=animation.FuncAnimation(fig,animate,repeat=False,blit=True,frames=n,
interval=50)
anim.save('barchart_animated_'+str(n)+'.mp4')
plt.show()
I must admit that I'm not pretty sure what I should do to remove this flaw. The only example I know of where the bars do not overlay in the frames is here (more exactly, I'm referring to the code of the first answer of the following link):
Dynamically updating a bar plot in matplotlib
It seems that I somehow have to tell the animation how it should set the height of each bar at each frame with the set_height-method. But as I said, I don't really know what's wrong in the above example. Thanks for any help!
Martin
The problem you have here is that you create a new barplot in every iteration of the animation. They will one by one be added to the plot, but since their height is shrinking over time, it may look as though only the first bar is present.
There are two ways to overcome this. First option is to clear the axes before plotting a new bar plot. This however will rescale the axis limits, which should then be constantly set to the same value.
The other option is to manipulate the one and only bar plot in the axes and adapt it's height for every frame. This is shown in the code below.
import matplotlib.pyplot as plt
from matplotlib import animation
def barlist(n):
return [1/float(n*k) for k in range(1,6)]
fig=plt.figure()
n=100 #Number of frames
x=range(1,6)
barcollection = plt.bar(x,barlist(1))
def animate(i):
y=barlist(i+1)
for i, b in enumerate(barcollection):
b.set_height(y[i])
anim=animation.FuncAnimation(fig,animate,repeat=False,blit=False,frames=n,
interval=100)
anim.save('mymovie.mp4',writer=animation.FFMpegWriter(fps=10))
plt.show()
Answers to the questions from the comments:
Blotting is a technique where all the parts of the figure which do not change are stored as a background. Then for each animated frame, only the changing parts are redrawn. This avoids the background to be redrawn from scratch and thus allows for much faster animations. Blitting will only affect the on-screen animation, because saving the animation to a file is not performed in real-time (and doesn't need to anyways).
Using blit=False here allows to make the code more simple because we do not need to care about the differences between the animation on screen and the one saved - they are just the same.
The enumerate function yields both the index as well as the object from the enumerated sequence. I did use it here, because it is a convenient way to obtain both in the same loop. It is not at all important here, you could alternatively do something like
for i in range(len(barcollection)):
barcollection[i].set_height(y[i])