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 !
Related
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.
I have a list of points, lets say as (x,y) pairs. I am trying to animate a plot so that each frame of the animation, a new point show up on the plot in a different color. Specifically on the 0th frame, the 0th point appears, on the the 1st frame, the 1st point appears, and so on. I would also like to have these points appear in a new color, specifically like a linear progression through a color palette as the points progress, so that you can "follow" the points by their color. This is similar to, and how I got as far as I am now: How can i make points of a python plot appear over time?. The first animation in the link is spot on, except without the points changing colors.
I am using matplotlib, matplotlib.pyplot, and FuncAnimation from matplotlib.animation
What I have already:
def plot_points_over_time(list_of_points):
num_points = len(list_of_points)
fig = plt.figure()
x, y = zip(*list_of_points)
plt.xlim(min(x),max(x))
plt.ylim(min(y),max(y))
colors = [plt.cm.gist_rainbow(each) for each in np.linspace(0,1,num_points)]
graph, = plt.plot([],[],'o')
def animate(i):
graph.set_data(x[:i+1],y[:i+1])
return graph
ani = FuncAnimation(fig, animate, frames = num_points, repeat = False, interval = 60000/num_points)
plt.show()
I can change the color of all of the points together on each frame by including the line graph.set_color(colors[i]) in the animate function, but not each point individually.
Figured it out with some digging and trial and error:
def plot_points_over_time(list_of_points):
num_points = len(list_of_points)
fig = plt.figure()
x, y = zip(*list_of_points)
plt.xlim(min(x),max(x))
plt.ylim(min(y),max(y))
colors = [plt.cm.gist_rainbow(each) for each in np.linspace(0,1,num_points)]
scat, = plt.plot([],[])
def animate(i):
scat.set_offsets(np.c_[x[:i+1], y[:i+1]])
scat.set_color(colors[:i+1])
return scat,
ani = FuncAnimation(fig, animate, frames = num_points, repeat = False, interval = 60000/num_points)
plt.show()
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/)
I am following a tutorial to plot in real time using python, for some reason my plot is not showing fully. I have no idea why because it is only 3 lines of code and they are exactly the same as the tutorial!
I want to run the code below but as expected I can see it moving but I can't see the entire graph. What is happening here?!
x = []
y = []
i = 0
plt.show()
while True:
x.append(i)
y.append(C3[i])
ax.plot(x, y, color='b')
fig.canvas.draw()
ax.set_xlim(left=max(0, i-50), right=i+50)
time.sleep(0.1)
i += 1
[edit]
Whenever I run
fig = plt.figure()
ax = fig.add_subplot(111)
fig.show()
I get
[IPKernelApp] WARNING | No such comm: bba1ac5ea0484ec7a6446924a4ff37a0
In my terminal
I have two different datasets with different (lat, lon) grid over a common region. I am trying to plot a contourf of one and quiver of another on a common basemap, and then animate this over time.
I have followed this http://matplotlib.org/basemap/users/examples.html and this https://github.com/matplotlib/basemap/blob/master/examples/animate.py.
So far I have:
m = Basemap(llcrnrlon=min(lon),llcrnrlat=min(lat),urcrnrlon=max(lon),urcrnrlat=max(lat),
rsphere=(6378137.00,6356752.3142),resolution='h',projection='merc')
# first dataset
lons, lats = numpy.meshgrid(lon, lat)
X, Y = m(lons, lats)
# second dataset
lons2, lats2 = numpy.meshgrid(lon2, lat2)
xx, yy = m(lons2, lats2)
#colormap
levels = numpy.arange(0,3,0.1)
cmap = plt.cm.get_cmap("gist_rainbow_r")
# create figure.
fig=plt.figure(figsize=(12,8))
ax = fig.add_axes([0.05,0.05,0.8,0.85])
# contourf
i = 0
CS = m.contourf(xx,yy,AUX[i,:,:],levels,cmap=cmap,extend='max')
cbar=plt.colorbar(CS)
# quiver
x = X[0::stp,0::stp] #plot arrows with stp = 2
y = Y[0::stp,0::stp]
uplt = U[i,0::stp,0::stp]
vplt = V[i,0::stp,0::stp]
Q = m.quiver(x,y,uplt,vplt,color='k',scale=15)
qk = ax.quiverkey(Q,0.1,0.1,0.5,'0.5m/s')
# continents
m.drawcoastlines(linewidth=1.25)
m.fillcontinents(color='0.8')
def updatefig(i):
global CS, Q
for c in CS.collections: c.remove()
CS = m.contourf(xx,yy,AUX[i,:,:],levels,cmap=cmap,extend='max')
uplt = U[i,0::stp,0::stp]
vplt = V[i,0::stp,0::stp]
Q.set_UVC(uplt,vplt)
anim = animation.FuncAnimation(fig, updatefig, frames=AUX.shape[0],blit=False)
plt.show()
Everything works fine for the first plot (i=0) but afterwards I only get the contourf animation without any quiver plot superimposed (but the quiverkey appears!)
Both animations separately work fine, but not together.
Is there a problem of having two different x,y on a basemap?
You can try ax.autoscale(False) before you plot the second part(quiver).
Hope it'll be helpful
I was able to work it out by adding the quiver plot inside the function and adding a Q.remove() after saving the plot.
It ended with something like:
def updatefig(i):
global CS, Q
for c in CS.collections: c.remove()
CS = m.contourf(xx,yy,AUX[i,:,:],levels,cmap=cmap,extend='max')
uplt = U[i,0::stp,0::stp]
vplt = V[i,0::stp,0::stp]
Q = m.quiver(x,y,uplt,vplt,color='k',scale=15)
# SAVE THE FIGURE
Q.remove() #after saving the figure
anim = animation.FuncAnimation(fig, updatefig, frames=AUX.shape[0],blit=False)
plt.show()
It works like I intended although I still can't find the answer I set_UVC() does not work with contourf...