I made an animation from the list of images saved as numpy arrays.
Then I want to add a text onto the animation like like a subtitle whose text changes for each frame but placing plt.text(some_string) only adds the string at the first iteration and it does not work if I change the passed string in the loop. Below is my attempt. Please note HTML is just for Jupyter Lab.
import matplotlib.animation as animation
from PIL import Image
from IPython.display import HTML
import matplotlib.pyplot as plt
folderName = "hogehoge"
picList = glob.glob(folderName + "\*.npy")
fig = plt.figure()
ims = []
for i in range(len(picList)):
plt.text(10, 10, i) # This does not add the text properly
tmp = Image.fromarray(np.load(picList[i]))
ims.append(plt.imshow(tmp))
ani = animation.ArtistAnimation(fig, ims, interval=200)
HTML(ani.to_jshtml())
You have also to add the text object to the list of artists for each frame:
import matplotlib.animation as animation
from PIL import Image
from IPython.display import HTML
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
ims = []
for i in range(10):
artists = ax.plot(np.random.rand(10), np.random.rand(10))
text = ax.text(x=0.5, y=0.5, s=i)
artists.append(text)
ims.append(artists)
ani = animation.ArtistAnimation(fig, ims, interval=200)
HTML(ani.to_jshtml())
Related
The following code display the image and audio in the top-bottom style:
Here is the test code:
import librosa
import matplotlib.pyplot as plt
import IPython.display as ipd
def plot_it(name, audio, sample_rate):
plt.figure(figsize=(8, 1))
plt.plot(audio)
plt.gca().set_title(name)
plt.show()
ipd.display(ipd.Audio(data=audio, rate=sample_rate))
Is it possible for changing the "top-bottom" style to "left-right" style for displaying the audio at the right side of the plt figure?
You can use a GridspecLayout which is similar to matplotlib's GridSpec. In order to direct to output into the needed grid cells, you can capture it using the Output widget:
import librosa
import matplotlib.pyplot as plt
import IPython.display as ipd
from ipywidgets import Output, GridspecLayout
def plot_it(name, audio, sample_rate):
grid = GridspecLayout(1, 2, align_items='center')
out = Output()
with out:
fig, ax = plt.subplots(figsize=(8, 1))
ax.plot(audio)
ax.set_title(name)
plt.close(fig)
ipd.display(ax.figure)
grid[0, 0] = out
out = Output()
with out:
ipd.display(ipd.Audio(data=audio, rate=sample_rate))
grid[0, 1] = out
ipd.display(grid)
name = 'nutcracker'
filename = librosa.example(name)
y, sr = librosa.load(filename)
plot_it(name, y, sr)
(It is essential to close the figure, otherwise you'll have double output of the figure. This is easier to do this using the OOP than the pyplot interface, that's why I changed your matplotlib code a bit)
I am trying to create a plotting object that produces an animated matplotlib pcolor plot with a polar projection. Currently the object can either create a set of polar plots or try to create an animation of those plots.
When creating the set of polar plots (but not the animation) the object works as planned.
The animation portion of the object is based on this example, which works on my system. Unfortunately the animation as implemented in my object is not working. There is a figure and an MP4 file produced for the animation but both the figure and the too-short animation both show just some mis-shaped axes.
Does anyone have a suggestion of how to capture this figure series in an animation when embedded in an object?
I am using python 3.7, matplotlib 3.03 on a windows 10 machine
The code for the object and the code to run its instantiation are given below.
class Polar_smudge(object):
# object for creating polar contour plots
def __init__(self, azimuth_grid, range_grid):
import numpy as np
self.azimuth_grid = np.deg2rad(azimuth_grid)
self.range_grid = range_grid
self.fig = None
self.ax = None
self.images = []
#------------------------------------------------------------------
def add_data(self, value_grid):
import numpy as np
self.value_grid = value_grid
self.value_grid[self.value_grid<=0] = np.nan
#------------------------------------------------------------------
def add_figure(self, value_grid):
import matplotlib.pyplot as plt
# make and set-up figure
fig, ax = plt.subplots(subplot_kw=dict(projection='polar'))
ax.set_theta_zero_location("N")
ax.set_theta_direction(-1)
ax.set_rlim([0,10])
# make plot
cax = ax.pcolor(self.azimuth_grid, self.range_grid, value_grid, cmap=plt.cm.viridis_r)
ax.grid()
plt.show()
#------------------------------------------------------------------
def start_figure(self):
import matplotlib.pyplot as plt
# make and set-up figure
if self.fig is None :
self.fig, self.ax = plt.subplots(111, subplot_kw=dict(projection='polar'))
self.ax[0].set_theta_zero_location("N")
self.ax[0].set_theta_direction(-1)
def update_figure(self, value_grid):
import matplotlib.pyplot as plt
# make figure and add to image list
self.images.append((self.ax[0].pcolor(self.azimuth_grid, self.range_grid, value_grid, cmap=plt.cm.viridis_r),))
def end_figure(self):
import matplotlib.animation as animation
# animate the figure list
im_ani = animation.ArtistAnimation(self.fig, self.images, interval=50, repeat_delay=3000,blit=True)
im_ani.save('smudge.mp4')
#============This runs the object ====================================
import numpy as np
azimuth_bins = np.linspace(0, 360, 360)
range_bins = np.linspace(0, 10, 30)
# make plotting azim range grids
range_grid, azimuth_grid = np.meshgrid(range_bins, azimuth_bins)
# this works but isnt what I want
good_smudge = Polar_smudge(azimuth_grid,range_grid)
for ix in range(3):
val_grid = np.random.randn(360,30)
good_smudge.add_figure(val_grid)
# this doesnt work
bad_smudge = Polar_smudge(azimuth_grid,range_grid)
bad_smudge.start_figure()
for ix in range(3):
val_grid = np.random.randn(360,30)
bad_smudge.update_figure(val_grid)
bad_smudge.end_figure()
In response to the comment from Earnest, I did some further refinement and it appears that the problem is not linked to being embedded in an object, and also that increasing the number of frames (to eg. 30) does not solve the problem. The code snippet below provides a more concise demonstration of the problem (but lacks the correctly produced figure output option).
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
azimuth_bins = np.linspace(0, 360, 60)
range_bins = np.linspace(0, 10, 30)
images = []
# make plotting azim range grids
range_grid, azimuth_grid = np.meshgrid(range_bins, azimuth_bins)
fig,ax = plt.subplots(111, subplot_kw=dict(projection='polar'))
ax[0].set_theta_zero_location("N")
ax[0].set_theta_direction(-1)
for ix in range(30):
val_grid = np.random.randn(60,30)
images.append((ax[0].pcolor(azimuth_grid, range_grid, val_grid, cmap=plt.cm.viridis_r),))
# animate the figure list
im_ani = animation.ArtistAnimation(fig, images, interval=50, repeat_delay=3000,blit=False)
im_ani.save('smudge2.mp4')
I am trying to change content of an image interactively using a slider (e.g. for applying a median operation with different kernel sizes).
While this works well if I only show one resulting image (cf commented lines), I run into trouble when using the subplot function, since the image will not get updated.
What am I missing?
%matplotlib inline
from ipywidgets import interact, widgets
import matplotlib.pyplot as plt
import warnings
from skimage.morphology import disk
from skimage.filters import rank
from skimage.color import rgb2gray
import skimage.data
def f(Median_Size):
selem = disk(int(Median_Size))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
img_median = rank.median(img_gray, selem=selem)
ax_neu.imshow(img_median, cmap="gray")
fig.canvas.draw()
#plt.imshow(img_median, cmap="gray") #This would work
#plt.show()
image = skimage.data.camera() #plt.imread("Test.png")
img_gray = rgb2gray(image)
fig = plt.figure(figsize=(6, 4))
ax_orig = fig.add_subplot(121)
ax_neu = fig.add_subplot(122)
ax_orig.imshow(img_gray, cmap="gray")
ax_neu.imshow(img_gray, cmap="gray")
interact(f, Median_Size=widgets.IntSlider(min=1,max=21,step=2,value=1))
Using %matplotlib notebook
Instead of the inline backend, you may use the notebook backend. This will allow to call figure.canvas.draw() as expected from running the code as a script. Replace the line %matplotlib inline by
%matplotlib notebook
and restart the Kernel.
Using display
You may display the newly changed figure after it has been changed. The drawback is that it creates the output twice. A workaround would then be to put interact in a new cell and capture the output from the first cell.
%%capture
%matplotlib inline
from ipywidgets import interact, widgets
from IPython.display import display
import matplotlib.pyplot as plt
import warnings
from skimage.morphology import disk
from skimage.filters import rank
from skimage.color import rgb2gray
import skimage.data
def f(Median_Size):
selem = disk(int(Median_Size))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
img_median = rank.median(img_gray, selem=selem)
ax_neu.imshow(img_median, cmap="gray")
fig.canvas.draw()
display(fig)
image = skimage.data.camera() #plt.imread("Test.png")
img_gray = rgb2gray(image)
fig = plt.figure(figsize=(6, 4))
ax_orig = fig.add_subplot(121)
ax_neu = fig.add_subplot(122)
ax_orig.imshow(img_gray, cmap="gray")
ax_neu.imshow(img_gray, cmap="gray")
In a new cell
interact(f, Median_Size=widgets.IntSlider(min=1,max=21,step=2,value=1));
The output would then look like:
I have a python animation script (using matplotlib's funcAnimation), which runs in Spyder but not in Jupyter. I have tried following various suggestions such as adding "%matplotlib inline" and changing the matplotlib backend to "Qt4agg", all without success. I have also tried running several example animations (from Jupyter tutorials), none of which have worked. Sometimes I get an error message and sometimes the plot appears, but does not animate. Incidentally, I have gotten pyplot.plot() to work using "%matplotlib inline".
Does anyone know of a working Jupyter notebook with a simple inline animation example that uses funcAnimation.
[Note: I am on Windows 7]
notebook backend
'Inline' means that the plots are shown as png graphics. Those png images cannot be animated. While in principle one could build an animation by successively replacing the png images, this is probably undesired.
A solution is to use the notebook backend, which is fully compatible with FuncAnimation as it renders the matplotlib figure itself:
%matplotlib notebook
jsanimation
From matplotlib 2.1 on, we can create an animation using JavaScript. This is similar to the ani.to_html5() solution, except that it does not require any video codecs.
from IPython.display import HTML
HTML(ani.to_jshtml())
Some complete example:
import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np
t = np.linspace(0,2*np.pi)
x = np.sin(t)
fig, ax = plt.subplots()
ax.axis([0,2*np.pi,-1,1])
l, = ax.plot([],[])
def animate(i):
l.set_data(t[:i], x[:i])
ani = matplotlib.animation.FuncAnimation(fig, animate, frames=len(t))
from IPython.display import HTML
HTML(ani.to_jshtml())
Alternatively, make the jsanimation the default for showing animations,
plt.rcParams["animation.html"] = "jshtml"
Then at the end simply state ani to obtain the animation.
Also see this answer for a complete overview.
There is a simple example within this tutorial here: http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-notebooks/
To summarise the tutorial above, you basically need something like this:
from matplotlib import animation
from IPython.display import HTML
# <insert animation setup code here>
anim = animation.FuncAnimation() # With arguments of course!
HTML(anim.to_html5_video())
However...
I had a lot of trouble getting that to work. Essentially, the problem was that the above uses (by default) ffmpeg and the x264 codec in the background but these were not configured correctly on my machine. The solution was to uninstall them and rebuild them from source with the correct configuration. For more details, see the question I asked about it with a working answer from Andrew Heusser: Animations in ipython (jupyter) notebook - ValueError: I/O operation on closed file
So, try the to_html5_video solution above first, and if it doesn't work then also try the uninstall / rebuild of ffmpeg and x264.
Another option:
import matplotlib.animation
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150
plt.ioff()
fig, ax = plt.subplots()
x= np.linspace(0,10,100)
def animate(t):
plt.cla()
plt.plot(x-t,x)
plt.xlim(0,10)
matplotlib.animation.FuncAnimation(fig, animate, frames=10)
Here is the answer that I put together from multiple sources including the official examples. I tested with the latest versions of Jupyter and Python.
Download FFmpeg ( http://ffmpeg.zeranoe.com/builds/ )
Install FFmpeg making sure that you update the environmental variable ( http://www.wikihow.com/Install-FFmpeg-on-Windows ).
Run this script in Jupyter below. The variable imageList is the only thing that you need to modify. It is an list of images (your input).
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from IPython.display import HTML
#=========================================
# Create Fake Images using Numpy
# You don't need this in your code as you have your own imageList.
# This is used as an example.
imageList = []
x = np.linspace(0, 2 * np.pi, 120)
y = np.linspace(0, 2 * np.pi, 100).reshape(-1, 1)
for i in range(60):
x += np.pi / 15.
y += np.pi / 20.
imageList.append(np.sin(x) + np.cos(y))
#=========================================
# Animate Fake Images (in Jupyter)
def getImageFromList(x):
return imageList[x]
fig = plt.figure(figsize=(10, 10))
ims = []
for i in range(len(imageList)):
im = plt.imshow(getImageFromList(i), animated=True)
ims.append([im])
ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000)
plt.close()
# Show the animation
HTML(ani.to_html5_video())
#=========================================
# Save animation as video (if required)
# ani.save('dynamic_images.mp4')
If you have a list of images and want to animate through them, you can use something like this:
from keras.preprocessing.image import load_img, img_to_array
from matplotlib import animation
from IPython.display import HTML
import glob
%matplotlib inline
def plot_images(img_list):
def init():
img.set_data(img_list[0])
return (img,)
def animate(i):
img.set_data(img_list[i])
return (img,)
fig = figure()
ax = fig.gca()
img = ax.imshow(img_list[0])
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=len(img_list), interval=20, blit=True)
return anim
imgs = [img_to_array(load_img(i)) for i in glob.glob('*.jpg')]
HTML(plot_images(imgs).to_html5_video())
Thank to Kolibril. I finally can run animation on Jupyter and Google Colab.
I modify some code which will generate animation of drawing random line instead.
import matplotlib.animation
import matplotlib.pyplot as plt
from itertools import count
import random
plt.rcParams["animation.html"] = "jshtml"
plt.rcParams['figure.dpi'] = 150
fig, ax = plt.subplots()
x_value = []
y_value = []
index = count();
def animate(t):
x_value.append(next(index))
y_value.append(random.randint(0,10))
ax.cla()
ax.plot(x_value,y_value)
ax.set_xlim(0,10)
matplotlib.animation.FuncAnimation(fig, animate, frames=10, interval = 500)
enter image description here
I have to create a group of matplotlib figures, which I would like to directly present in a PDF report without saving them as a file.
The data for my plots is stored in a Pandas DataFrame:
Right now I do not know other better option than first save the image and use it later.
I am doing something like that:
import matplotlib.pylab as plt
from reportlab.platypus import BaseDocTemplate, Image
for index, row in myDataFrame.iterrows():
fig = plt.figure()
plt.plot(row['Xvalues'], row['Yvalues'],'o', color='r')
fig.savefig('figure_%s.png' % (row['ID']))
plt.close(fig)
text = []
doc = BaseDocTemplate(pageName, pagesize=landscape(A4))
for f in listdir(myFolder):
if f.endswith('png'):
image1 = Image(f)
text.append(image1)
doc.build(text)
Here is the best solution provided by matplotlib itself:
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
with PdfPages('foo.pdf') as pdf:
#As many times as you like, create a figure fig and save it:
fig = plt.figure()
pdf.savefig(fig)
....
fig = plt.figure()
pdf.savefig(fig)
VoilĂ
Find a full example here: multipage pdf matplotlib
I think you can save the figure into a buffer using io.BytessIO and use that in platypus. Something like this perhaps?
import io
import matplotlib.pylab as plt
from reportlab.platypus import BaseDocTemplate, Image
buffers = []
for index, row in myDataFrame.iterrows():
fig = plt.figure()
plt.plot(row['Xvalues'], row['Yvalues'],'o', color='r')
mybuffer = io.BytesIO()
fig.savefig(mybuffer, format = 'pdf')
mybuffer.seek(0)
buffers.append(mybuffer)
plt.close(fig)
text = []
doc = BaseDocTemplate(pageName, pagesize=landscape(A4))
doc.build(buffers)
using my package autobasedoc https://pypi.org/project/autobasedoc/ your example would look like that:
from autobasedoc import autorpt as ar
from autobasedoc import autoplot as ap
#ap.autoPdfImg
def my_plot(index, row, canvaswidth=5): #[inch]
fig, ax = ap.plt.subplots(figsize=(canvaswidth,canvaswidth))
fig.suptitle(f"My simple plot {index}", fontproperties=fontprop)
ax.plot(row['Xvalues'], row['Yvalues'],label=f"legendlabel{index}")
return fig
doc = ar.AutoDocTemplate(pageName)
content = []
for index, row in myDataFrame.iterrows():
content.append(my_plot(index, row))
doc.build(content)