Matplotlib and Celluloid show strange behavior on Jupyter notebook - python

I am trying to animate the results of a simulation performed with Python. To do so, I'm using matplotlib to generate the frames of the animation and then I collect them with the Camera class from celluloid library. The code that generates the animation is the following:
fig = plt.figure()
ax = plt.gca()
ax.set_aspect('equal')
camera = Camera(fig)
for i in range(result.t.size):
if i % 10 == 0:
x = result.y[0, i]
y = result.y[1, i]
plt.scatter(x, y, s = 100, c = 'red')
plt.xlim(-3, 3)
plt.ylim(-3, 3)
plt.grid()
camera.snap()
animation = camera.animate(blit = False, interval = 10)
HTML(animation.to_html5_video())
The last part that generates an HTML5 video allows for watching the animation in a Jupyter notebook on the web. However, I get the following output:
The first output is the corresponding animation, which is working good. The second is just a static empty plot. So I have two questions:
Where does the second plot come from and how can I remove it?
The animation is not showing any grid, though I requested it via plt.grid() on each frame. Why is that happening?
Thanks in advance for any help.

Related

Displaying scatterplot points by points in jupyter notebook

I am trying to display a scatterplot points by points from two arrays :
x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5]
I would like to display the point (0,0.5) and add successively the other points ((0.5,1) through (0.5,10)) to the existing plot.
It could be considered as an animated scatterplot indenting points by points.
So far, I have tried the following solutions :
xi=[]
yi=[]
for i in range(10):
xi.append(x[i])
yi.append(y[i])
plt.axhline(y=0.5,color="black",linestyle = '-')
plt.scatter(xi,yi,marker = '+', color="red")
plt.legend()
plt.pause(0.01)
plt.show()
which works perfectly fine in my script (spyder IDE) but not in my jupyter notebook.
Or with the animation function from matplotlib :
frames=20
fig = plt.figure()
ax = plt.gca()
x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5]
def scatter_ani(i):
plt.scatter(x[i], y[i],marker = '+', color="red",label="chocs")
anim = animation.FuncAnimation(fig, scatter_ani, frames = frames, interval=50)
anim.save(r"mypath/myanim.gif",writer = animation.PillowWriter(fps=30))
and then,
![mygif](myanim.gif)
in a markdown cell.
How can I display this simple animation in my notebook?
Thank you for your time, I look forward to your insights !

how to show multiple graphs at once? (class)

Hi everyone:) I would like to ask for some help to make a class that I can use to plot graphs. i have an excel sheet with different countries and their corresponding air pollution levels. i need to plot graphs for each country. this is the code used to plot my graphs:
import matplotlib.pyplot as plt
import numpy as np
x = df_full_filtered.loc[(df_full_filtered['AirPollutant'] == 'PM10') & (df_full_filtered['Country']
== 'Italy')]['AirPollutionLevel']
plt.style.use('ggplot')
plt.hist(x, bins=80)
plt.show()
y = df_full_filtered.loc[(df_full_filtered['AirPollutant'] == 'PM10') & (df_full_filtered['Country']
== 'Germany')]['AirPollutionLevel']
plt.style.use('ggplot')
plt.hist(y, bins=80)
plt.show()
everytime i run my code, it stops running everytime it reaches the plt.show code and wont continue running till you manually close the popup window with the first graph. is there any way i can surpass this?
edit: i tried putting both codes for x and y under each other and inserting plt.plot(x,y) but they have different shapes (rows/columns in the excel file)
thanks
You need to create two figures.
Method 1
data = [i**2 for i in range(100)]
plt.figure(1)
plt.hist(data, bins = 5)
plt.figure(2)
plt.hist(data, bins = 10)
plt.show()
Method 2
data = [i**2 for i in range(100)]
fig1, ax1 = plt.subplots()
ax1.hist(data, bins = 5)
fig2, ax2 = plt.subplots()
ax2.hist(data, bins = 10)
plt.show()
(If you need, you can call them the same name, i.e. the second figure and axes could be named fig1 and ax1, as well.)
Method 1 is the direct answer to your code. Method 2 is another way of using Matplotlib. (see https://matplotlib.org/matplotblog/posts/pyplot-vs-object-oriented-interface/)

Animation of Precomputed Interactive Graphs Using Matplotlib

I created several plots using the following code:
a = np.arange(1,6)
b = np.arange(2, 11, 2)
c = np.arange(100, 1000, 200)
d = np.arange(0.2, 1.1, 0.2)
figs = []
for i in np.arange(1, 6):
fig, ax = plt.subplots()
ax.bar(a, b/i, width = d/10)
ax.scatter(a, b/i, s=c*i)
figs.append(fig)
fig = plt.figure()
ani = matplotlib.animation.ArtistAnimation(fig, figs)
plt.show()
And the graphs look like
I put the figure objects into a list and used the ArtistAnimation feature, but nothing seems to show. I'm also adding interactive features to each graph such as hover boxes so I can't just save the plots and make gifs. Can someone point out where I need to change my code? Also, is there any way to turn off the display of graphs when I generate them so that there won't be too many different graphs displaying at the same time?

Python Several problems of produce GIF by using animation.FuncAnimation

I encountered several problems when I was trying to produce a GIF by using animation function in Python.
Here is my code:
import matplotlib.pyplot as plt
import random
import matplotlib.animation as animation
xdata = []
ydata = []
fig, ax = plt.subplots()
line, = ax.plot(xdata, ydata, marker='o', markeredgewidth=9)
n = -1
def data_gen():
global n
while True:
xdata.clear()
ydata.clear()
for i in range(3):
xdata.append(random.randint(0, 10))
ydata.append(random.randint(0, 10))
n += 1
print('The', n, 'generation')
yield xdata, ydata
def init():
plt.grid()
line.set_linestyle('None')
ax.set_xlim(0, 20)
ax.set_ylim(0, 20)
return line,
def animate(data):
line.set_data(data)
print('data', data)
return line,
ani = animation.FuncAnimation(fig=fig, func=animate, frames=data_gen, init_func=init, interval=200, blit=False)
ani.save('clear list.gif', writer='imagemagick')
plt.show()
Problem 1: There has been a pause (about 10 seconds) since the code started running, in the stage of 0–pause, the GIF can be saved, however, there is a black flash on saved GIF.
Problem 2: At the stage start–pause, I can not see the plot on the screen, after this pause, the plot appeared, the program goes into the normal stage.
Problem 3: I put the code plt.grid() in the function init. When the code is running, I cannot see grid on the plot, however, grid can be seen on the saved plot, why? If I add another code plt.grid() before the last code plt.show(), at this time, the grid will be shown on the plot.
Can someone tell me why this happens?
The code runs in:
IDE: Pycharm 2019.3.4 Professional Edition
Interpreter: Python 3.7
OS: Windows 10
Figure captured when the black shadow appears:

How to display an animated graph using Matplotlib.animation.FuncAnimation in PyCharm on macOS?

I am trying to use matplotlib.animation.FuncAnimation to display an animated graph (not through the terminal). I am using PyCharm Professional 2019.2 on macOS 10.14.6
I haven't found any solutions that would work for PyCharm on macOS.
I've tried a couple of things:
Using an alternative to FuncAnimate Animating with matplotlib without animation function
Adding
import matplotlib
matplotlib.use("TkAgg")
as suggested in Matplotlib animation not displaying in PyCharm. This causes my PyCharm to crash and brings me to the macOS login screen.
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Create figure for plotting
figure = plt.figure()
axis = figure.add_subplot(1, 1, 1)
xs = []
ys = []
# This function is called periodically from FuncAnimation
def animate(i, xs, ys):
# Add x and y to lists
xs.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
ys.append(dt.datetime.now().strftime('%H:%M:%S.%f'))
# Limit x and y lists to 20 items
xs = xs[-20:]
ys = ys[-20:]
# Draw x and y lists
axis.clear()
axis.plot(xs, ys)
# Format plot
plt.xticks(rotation=45, ha='right')
plt.subplots_adjust(bottom=0.30)
plt.title('Data over Time')
plt.ylabel('Data')
# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(figure, animate, fargs=(xs, ys), interval=1000)
plt.show()
This code just simply graphs a linear function based on time (both axes)
When compiling through the terminal, the graph is working flawlessly. PyCharm for some reason doesn't want to graph it. Any solutions for macOS?

Categories