Display animation outside of jupyter notebook - python

I want to use Jupyter notebook to host my code for a presentation, but I don't want to embed animation into the notebook. (Because it is time-consuming to embed the video.) I want to run the cells and pop up a screen as if I am running the code in the terminal.
from matplotlib.animation import FuncAnimation
from matplotlib.pyplot import plot, show, subplots, title # annotate
from IPython.display import HTML
anim = FuncAnimation(fig, update, frames=numlin, interval=100, fargs=(
d, g, lr_D, lr_G, hasFake, speed, show_sample),
init_func=init, blit=True, repeat=0)
HTML(anim.to_html5_video())
Why using the notebook? The main reason to use the notebook is that I have many different setups for an experiment. I want to use different cells to represent different configurations, and if people want to see results from a particular configuration, I can run it right away.
Time difference. The HTML function takes over a minute to generate the video I need. While in the terminal, the animation would just start. I want to prototype quickly during a meeting while the audience asks to show the results from different initial conditions.
There is also an unexpected behavior from the notebook. The video from the notebook is different from that popped up in the terminal. The video in the notebook did not erase existing frames while drawing, making the animation looks messy and cannot track the trajectory as good as its counterpart.
Animation from the notebook's output
Animation from the terminal's output
This drawing behavior is another reason why I don't want to use the notebook to display the animation.
Will the notebook needs to show other plots. I hope so, but it is not necessary. I can open another notebook for just plots if needed.
Please let me know if I do not explain it well.

Animation inside of notebook
Reading the question, I wonder if you are aware of the %matplotlib notebook backend. While it will show the animation inside the notebook, I feel that it would suit all the described needs.
%matplotlib notebook
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
a = np.random.rand(10,4)
fig, ax =plt.subplots()
ax.axis([0,1,0,1])
points1, = plt.plot([],[], ls="", marker="d", color="indigo")
points2, = plt.plot([],[], ls="", marker="o", color="crimson")
def update(i):
points1.set_data(a[i:i+2,0],a[i:i+2,1])
points2.set_data(a[i:i+2,2],a[i:i+2,3])
return points1, points2
anim = FuncAnimation(fig, update, frames=len(a)-1, repeat=True)
Note that using this kind of animation, where the data is updated with set_data is showing the same whether saved to video or shown on screen.
Hence, if it wasn't for the time it takes to replace the video, you could well use it in the initially shown way, deleting %matplotlib notebook and adding
from IPython.display import HTML
HTML(anim.to_html5_video())
If using matplotlib 2.1, you may also opt for a JavaScript animation,
from IPython.display import HTML
HTML(ani.to_jshtml())
Animation in new window
If you want to have a window appearing, you should neither use %matplotlib inline nor %matplotlib notebook, instead replace the first line in the above code by
%matplotlib tk

Related

matplotlib how to show plot when not in jupyter notebook

I am working with a legacy codebase that uses python modules together with jupyter notebook. The plotting functionality is contained in the python modules eg:
from matplotlib import pyplot as plt
class SomeClass(object):
def plot(self, x_data, y_data)
plt.plot(x_data, y_data)
#I added this code to show plot if not using notebook
plt.show()
I would rather not add ply.show() to all the places in the legacy code where pyplot is used.
Is there a global way to 'force' pyplot to show when get_ipython() is not in the global context?
If you work in interactive mode, plot is shown directly. You turn on interactive mode by calling plt.ion() once. Thus you still have to modify your legacy code, by adding this command, but that needs only to be done once, in the beginning of the program.

plt.ioff() isn't working. How do I plot several different graphs

plt.ioff()
for i in range(0,len(variableList)):
graph = lag1['VDC'].rolling(window=24).corr(other=lag1[variableList[i]])
plt.title(variableList[i])
plt.plot(graph)
plt.axhline(y=0)
plt.savefig(variableList[i])
I want to plot several different independent graphs. The default is in interactive mode where each new graph is plotted on the previous one. I read the document and found that I need to use plt.ioff(). However adding this line doesn't change anything.
If you try the example in non-interactive example, Usage Guide, the output is a set of three graphs indeed. Furthermore, plt.ioff() doesn't work if you set %matplotlib inline.
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.show()
However, it saves plots with lines accumulated if you use plt.savefig.
%matplotlib inline
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.savefig(f'{i}.png')
Also, it doesn't work if:
%matplotlib auto
plt.ioff()
for i in range(3):
plt.plot(np.random.rand(10))
plt.show()
So, for non-interactive figures, you should always use object-oriented (OO) style to avoid such issues:
%matplotlib auto
plt.ioff()
for i in range(3):
fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
fig.savefig(f'{i}.png')
The interactive mode is used to obtain an event loop while continuiung the execution of the script. This can be useful to update a plot at several different points in a script, for doing quick animations or for working from within the console.
The interactive mode has nothing to do with new figures being created. I.e. you can have several figures or only one figure, both with interactive mode on or off.
To obtain a new figure in pyplot use
plt.figure()
pyplot commands executed after that will apply to this new figure.
The pyplot tutorial has a chapter on Working with multiple figures and axes, where this is explained in detail.

Draw matplotlib plot to PNG in Jupyter when inline matplotlib is enabled

I am drawing a confusion matrix heatmap in Jupyter using code similar to the example here using imshow
Matplotlib is set to draw plots inline.
This works fine for outputting to the cell in the notebook, but I want to not output to the cell but instead get PNG data (ideally raw, not saved to a file) in this case only, not in general (in general I want matplotlib to display inline).
I'm not quite sure how to do that; examples I've seen seem to be global in nature (e.g. calling matplotlib.use() before importing pyplot).
Is this possible? How?
A simple way to not display the plot inline, is to use plt.close() at the end of the cell.
import matplotlib.pyplot as plt
%matplotlib inline
plt.plot([1,2,3],[1,2,3])
plt.savefig("image.png")
plt.close()
Turn off interactive mode:
plt.ioff()
To reactivate inline images, use
plt.ion()
%matplotlib inline
To save the PNG image as bytes, but not to a file, pass a file-like io.BytesIO object to plt.savefig instead of a file:
import io
data = io.BytesIO()
plt.savefig(data)

Seaborn Plot doesn't show up

I am creating a bar chart with seaborn, and it's not generating any sort of error, but nothing happens either.
This is the code I have:
import pandas
import numpy
import matplotlib.pyplot as plt
import seaborn
data = pandas.read_csv('fy15crime.csv', low_memory = False)
seaborn.countplot(x="primary_type", data=data)
plt.xlabel('crime')
plt.ylabel('amount')
seaborn.plt.show()
I added "seaborn.plt.show() in an effort to have it show up, but it isn't working still.
You should place this line somewhere in the top cell in Jupyter to enable inline plotting:
%matplotlib inline
It's simply plt.show() you were close. No need for seaborn
I was using PyCharm using a standard Python file and I had the best luck with the following:
Move code to a Jupyter notebook (which can you do inside of PyCharm by right clicking on the project and choosing new - Jupyter Notebook)
If running a chart that takes a lot of processing time it might not have been obvious before, but in Jupyter mode you can easily see when the cell has finished processing.

My graph is not showing up and my iPython Notebooks never stops working

When I run the code below my iPython Notebooks starts working on it (I see black dot in the top right corner), but it never stops. I cannot stop it either by pressing button with the black square.
I opened my other notebook and it shows the histogram without any problem.
What can be the reason?
Thank you.
import matplotlib.pyplot as plt
from numpy.random import normal
gaussian_numbers = normal(size=1000)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
UPDATE: Created a new notebook. Passed all the code from the previous notebook (including code that gets the data from the internet). Can any other code affect working and displaying the histogram?
There is not other code working when I run histogram.
yo need to use%matplotlib inline
%matplotlib inline
import matplotlib.pyplot as plt
from numpy.random import normal
gaussian_numbers = normal(size=1000)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
see this other thread to automatically do this on the IPython configuration Automatically run %matplotlib inline in iPython Notebook

Categories