matlibplot real-time plotting doesn't work - python

I have created the script below for real-time data plotting. But the plot which shows up is empty. Could you tell me what's the case?
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
from itertools import count
import random
style.use('fivethirtyeight')
fig = plt.figure()
axl = fig.add_subplot(1,1,1)
x_vals = []
y_vals = []
index = count()
def animate(i):
x_vals.append(next(index))
y_vals.append(random.randint(0, 5))
axl.clear()
axl.plot(x_vals,y_vals)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
I'm using python 3.8, matlibplot 3.1.2 and PyCharm as IDE.

Related

Plotting a live graph using matplotlib

I am trying a code to plot a live graph but i always land up with an empty plot. Here is my code :
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib import style
import random
style.use('fivethirtyeight')
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
y = random.randint(0,100) # generate random data
x = i # set x as iteration number
ax1.clear()
ax1.plot(x, y, 'ro')
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
I get warning but i am using plt.show() to show animation. Not sure what i am doing wrong :
UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you have outputted the Animation using `plt.show()` or `anim.save()`.
warnings.warn(

Matplotlib animation not showing any plot

I am trying to make an animation in 3D using Matplotlib and mpl_toolkits. For starter, I am trying to make an animation of a shifting cos wave. But when I run the program, the plot is completely empty. I have just started learning matplotlib animations, so I don't have in-depth knowledge of it. Here is my code:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib.animation as animation
fig = plt.figure()
ax = Axes3D(fig)
line, = ax.plot([],[])
print(line)
X = np.linspace(0, 6*math.pi, 100)
def animate(frame):
line.set_data(X-frame, np.cos(X-frame))
return line
anim = animation.FuncAnimation(fig, animate, frames = 100, interval = 50)
plt.show()
Here is the output:
What is wrong with my code? Why am I not getting any output?
There are two issues with your code:
use set_data_3d to update the data of a Line3D object instead of set_data
initialize the Axes3D scales before starting the animation
This should work:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
import matplotlib.animation as animation
fig = plt.figure()
ax = Axes3D(fig)
# initialize scales
ax.set_xlim3d(0, 6 * math.pi)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(0, 100)
X = np.linspace(0, 6 * math.pi, 100)
line, = ax.plot([], [], [])
def animate(frame):
# update Line3D data
line.set_data_3d(X, np.cos(X - frame), frame)
return line,
anim = animation.FuncAnimation(fig, animate, frames = 20, interval = 50)
plt.show()
and yield an animation like this (I have truncated the number of frames to reduce image file size).

How to make jupyter HTML-matplotlib animation with seaborn heatmap?

I trying to make HTML(anim.to_html5_video) animation work in jupyter with seaborn heatmap.
First, I get working working samples from documentation, and make "pure matplotlib" image map animated example, it worked, with small problem ("parasite output" in animation cell)
Then, I tried to make it work with seaborn.heatmap… but failed. Animation looks like "infinite mirror" — obviously something wrong with matplotlib axes/plot composition, but I can't get it.
Common initialization cell:
import pandas as pd
import seaborn as sns
import numpy as np
%matplotlib inline
#%matplotlib notebook # Tried both, not needed for animation.
import matplotlib.pyplot as plt
from matplotlib import animation, rc
from IPython.display import HTML
Animation worked, but "unwanted static output image exists":
fig, ax = plt.subplots()
nx = 50
ny = 50
line2d, = ax.plot([], [], lw=2)
def init():
line2d.set_data([], [])
ax.imshow(np.zeros((nx, ny)))
return (line2d,)
def animate(i):
data = np.random.rand(nx, ny)
ax.set_title('i: ' + str(i))
ax.imshow(data)
return (line2d,)
anim = animation.FuncAnimation(fig, animate, init_func=init, frames=10, interval=1000, blit=False)
HTML(anim.to_html5_video())
So, looks that all OK with my jupyter setup (packages, ffmpeg, etc).
But, I cannot get how to make it with seaborn.heatmap:
fig, ax = plt.subplots()
nx = 50
ny = 50
line2d, = ax.plot([], [], lw=2)
ax_global = ax
def init_heatmap():
line2d.set_data([], [])
sns.heatmap(np.zeros((nx, ny)), ax=ax_global)
return (line2d,)
def animate_heatmap(i):
data = np.random.rand(nx, ny)
sns.heatmap(data, ax=ax_global)
ax.set_title('Frame: ' + str(i))
return (line2d,)
anim = animation.FuncAnimation(fig, animate_heatmap, init_func=init_heatmap,
frames=10, interval=1000, blit=True)
HTML(anim.to_html5_video())
Both samples ready to test on github
Of course, I want to see animation with random map and "stable heat-axes"
but get this
https://vimeo.com/298786185/
You can toggle the "colorbar". From the Seaborn.heatmap documentation, you need to change sns.heatmap(data, ax=ax_global) to sns.heatmap(data, ax=ax_global, cbar=False) and also do the same inside the init_heatmap().

Not able to plot real time graph using matplotlib

I have written the following code with the help of online search. My intention here is to get a real time graph with time on x axis and some randomly generated value on y axis
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
def animate(i):
xar = []
yar = []
x,y = time.time(), np.random.rand()
xar.append(x)
yar.append(y)
ax1.clear()
ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()
With the above code I just see the range of y axis changing continuously and the graph will not appear in the figure.
The problem is that you never update xvar and yvar. You can do that by moving the definitions of the lists outside the definition of animate.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
xar = []
yar = []
def animate(i):
x,y = time.time(), np.random.rand()
xar.append(x)
yar.append(y)
ax1.clear()
ax1.plot(xar,yar)
ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

Matplotlib FuncAnimation only draws one frame

I am trying to do an animation using the FuncAnimation module, but my code only produces one frame and then stops. It seems like it doesn't realize what it needs to update. Can you help me what went wrong?
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
def animate(i):
PLOT.set_data(x[i], np.sin(x[i]))
print("test")
return PLOT,
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x = np.linspace(0,2*np.pi,100)
fig = plt.figure()
sub = fig.add_subplot(111, xlim=(x[0], x[-1]), ylim=(-1, 1))
PLOT, = sub.plot([],[])
def animate(i):
PLOT.set_data(x[:i], np.sin(x[:i]))
# print("test")
return PLOT,
ani = animation.FuncAnimation(fig, animate, frames=len(x), interval=10, blit=True)
plt.show()
You need to keep a reference to the animation object around, otherwise it gets garbage collected and it's timer goes away.
There is an open issue to attach a hard-ref to the animation to the underlying Figure object.
As written, your code well only plot a single point which won't be visible, I changed it a bit to draw up to current index

Categories