jwkvam / celluloid Goto Github PK
View Code? Open in Web Editor NEW:movie_camera: Matplotlib animations made easy
License: MIT License
:movie_camera: Matplotlib animations made easy
License: MIT License
Examples => Images => 'ax.imshow(rgb)' should be 'plt.imshow(rgb)'
def generate_frame(a, s, d, j, g, t_win, f):
plt.clf()
plt.plot(range(a), [i*i for i in range(a)])
return f
plt.ioff()
fig = plt.figure(figsize=(8, 6))
camera = Camera(fig)
for i in range(10):
generate_frame(i*10, 0, 0, 0, 0, 0, f=fig)
camera.snap()
animation = camera.animate()
HTML(animation.to_html5_video())
This does not work. The resultant animation shows only the final frame.
The extra parameters in the generate_frame function are leftovers from my real function, but should not matter.
Is it possible to have a different title set for each frame used in the animation, e.g. for a series of scatterplots?
I tried to save the animation from the minimal example as a .mp4 file.
import matplotlib.pyplot as plt
from celluloid import Camera
fig = plt.figure()
camera = Camera(fig)
for i in range(10):
plt.plot([i] * 10)
camera.snap()
animation = camera.animate()
animation.save("test.mp4", writer='ffmpeg')
The resulting test.mp4 is missing the second to last frame (i=8).
Why does this happen and how can I avoid this issue?
If I replace the last line in the code by ani.save("test.gif", writer='imagemagick')
, test.gif contains all frames.
When I use animation.save('out.gif')
without specifying writer, it seems that celluloid would use ffmpeg
as the default writer, thus resulting in an error (it tries to mux H.264 into GIF). Think that default writer should be specified for each post-fix.
It seems the title is not being animated as the rest of the figure.
In my usage, it just displayed the last value during all video.
x = 3.5*np.ones(2)
samples = x
fig = plt.figure()
camera = Camera(fig)
plt.scatter(x[0], x[1], s=30, c='pink', edgecolor='red')
for i in range(200):
x[0] = np.random.normal(a*x[1], 1) # mu=ax[1], sigma=1
x[1] = np.random.normal(a*x[0], 1)
samples = np.append(samples, (x))
samples = samples.reshape((-1, x.shape[0]))
plt.scatter(samples[:i, 0], samples[:i, 1], s=10, c='pink', alpha=0.7, edgecolor='red')
t2 = plt.scatter(x[0], x[1], s=30, c='red', edgecolor='blue')
plt.legend(t2, [f'New Point: {i}'])
camera.snap()
animation = camera.animate(blit=False, interval=150)
animation.save('celluloid_minimal.gif', writer='pillow')
Legend Error
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-158-32af401ce45e> in <module>()
15 t2 = plt.scatter(x[0], x[1], s=30, c='red', edgecolor='blue')
16 print(type(t2))
---> 17 plt.legend(t2, [f'New Point: {i}'])
18 # plt.legend()
19 camera.snap()
2 frames
/usr/local/lib/python3.6/dist-packages/matplotlib/pyplot.py in legend(*args, **kwargs)
2683 @docstring.copy(Axes.legend)
2684 def legend(*args, **kwargs):
-> 2685 return gca().legend(*args, **kwargs)
2686
2687
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_axes.py in legend(self, *args, **kwargs)
404 if len(extra_args):
405 raise TypeError('legend only accepts two non-keyword arguments')
--> 406 self.legend_ = mlegend.Legend(self, handles, labels, **kwargs)
407 self.legend_._remove_method = self._remove_legend
408 return self.legend_
/usr/local/lib/python3.6/dist-packages/matplotlib/legend.py in __init__(self, parent, handles, labels, loc, numpoints, markerscale, markerfirst, scatterpoints, scatteryoffsets, prop, fontsize, borderpad, labelspacing, handlelength, handleheight, handletextpad, borderaxespad, columnspacing, ncol, mode, fancybox, shadow, title, title_fontsize, framealpha, edgecolor, facecolor, bbox_to_anchor, bbox_transform, frameon, handler_map)
457 # trim handles and labels if illegal label...
458 _lab, _hand = [], []
--> 459 for label, handle in zip(labels, handles):
460 if isinstance(label, str) and label.startswith('_'):
461 cbook._warn_external('The handle {!r} has a label of {!r} '
I am using celluloid to plot a function over 17 years and i love it so far, it works great!
I have one small problem though, the edges of my plot disappear after the first loop. I have attached images of how this looks.
First loop:
Second loop:
I am using cartopy and matplotlib in jupyter notebook and this is my code for the animation:
`
import matplotlib
matplotlib.use('Agg')
from IPython.display import HTML
from celluloid import Camera
fig=plt.figure(figsize=(9,5))
cmap=matplotlib.cm.RdBu_r
norm=matplotlib.colors.Normalize(vmin=0, vmax=50)
ax=plt.axes(projection=ccrs.PlateCarree(),extent=[-180, 180, -90, 90])
ax.set_xticks([-180, -120, -60, 0, 60, 120, 180], crs=ccrs.PlateCarree())
ax.set_yticks([-90, -60, -30, 0, 30, 60, 90], crs=ccrs.PlateCarree())
plt.xlabel('Longitude [deg]')
plt.ylabel('Latitude [deg]')
camera = Camera(fig)
for i in range(0,(stop-start)+1):
ax.coastlines()
plt.scatter(nphi[i], nthe[i], c=mag[i], s=40, norm=norm, cmap=cmap, edgecolor="k")
ax.text(0, 1.05, 'Global Observatory Plot of SV magnitude from target year '
+ str(start+i) + ' in the dB_' + out + '-direction', fontsize=9, transform=ax.transAxes)
camera.snap()
cbar=plt.colorbar()
cbar.set_label('Magnitude of SV [nT/yr$^2$]')
animation = camera.animate(interval=800)
animation.save('Figures/GlobalSVMag.mp4')
HTML(animation.to_html5_video())
`
Is there a way to make the edge appear all the way through the animation?
I am trying to plot some iterative algorithm. I have multiple subplots and want to annotate the entire figure with a text Iteration <i>
where i
is an integer.
The text of all frames is displayed over each other instead of just one text per plot.
I want to record the process of the approximation of a function, It is tedious to plot the approximated function in the loop if I have plotted it before. So could I prepare something including the function before the loop and just hold on to it instead of redrawing it. (like the command hold on
in MATLAB)
I think this can also make FuncAnimation
easier to use. I need to figure out if it's worthwhile.
FuncAnimation
with celluloid
save on memoryIs there a way to view videos in google colab?
I tried running your simple example and I am getting the following error:
BrokenPipeError: [Errno 32] Broken pipe
as well as:
subprocess.CalledProcessError: Command '['ffmpeg', '-f', 'rawvideo', '-vcodec', 'rawvideo', '-s', '640x480', '-pix_fmt', 'rgba', '-r', '10.0', '-loglevel', 'error', '-i', 'pipe:', '-vcodec', 'h264', '-pix_fmt', 'yuv420p', '-y', 'simple.mp4']' returned non-zero exit status 1.
Do you know what could be causing this? I am using python 3.9, if that might be the issue.
Hi!
I wonder if celluloid is able to be used in Jupyter Notebook? I've tryied to run your example but it have not shown anything. Can I use celluloid and jupyter togheter?
Thanks!
FuncAnimation
)Used the minimal example and getting this error. Any thoughts on how to fix?
Pip'ed celluloid and ran below code and nothing happened....
fig = plt.figure()
camera = Camera(fig)
for i in range(10):
plt.plot([i] * 10)
camera.snap()
animation = camera.animate()
Hi - love this package.
Just wondering why i'm getting the error: "unknown file extension: .mp4"
it's also happening for all other file formats i'm inputting.
Any ideas?
Specifically, the error occurs as follows:
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\anaconda3\lib\site-packages\PIL\Image.py in save(self, fp, format, **params)
2081 try:
-> 2082 format = EXTENSION[ext]
2083 except KeyError:
KeyError: '.mp4'
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-114-513938de0b62> in <module>
64
65 animation = camera.animate()
---> 66 animation.save(r'C:\Users\61424\Documents\GitHub\CODE\Data\Figures\Functional Connectivity\'animation.mp4')
~\anaconda3\lib\site-packages\matplotlib\animation.py in save(self, filename, writer, fps, dpi, codec, bitrate, extra_args, metadata, extra_anim, savefig_kwargs, progress_callback)
1154 progress_callback(frame_number, total_frames)
1155 frame_number += 1
-> 1156 writer.grab_frame(**savefig_kwargs)
1157
1158 # Reconnect signal for first draw if necessary
~\anaconda3\lib\contextlib.py in __exit__(self, type, value, traceback)
117 if type is None:
118 try:
--> 119 next(self.gen)
120 except StopIteration:
121 return False
~\anaconda3\lib\site-packages\matplotlib\animation.py in saving(self, fig, outfile, dpi, *args, **kwargs)
230 yield self
231 finally:
--> 232 self.finish()
233
234
\anaconda3\lib\site-packages\matplotlib\animation.py in finish(self)
575 self._frames[0].save(
576 self._outfile, save_all=True, append_images=self._frames[1:],
--> 577 duration=int(1000 / self.fps), loop=0)
578
579
~\anaconda3\lib\site-packages\PIL\Image.py in save(self, fp, format, **params)
2082 format = EXTENSION[ext]
2083 except KeyError:
-> 2084 raise ValueError("unknown file extension: {}".format(ext))
2085
2086 if format.upper() not in SAVE:`
ValueError: unknown file extension: .mp4
```
Running the basic example:
import matplotlib
from matplotlib import pyplot as plt
from celluloid import Camera
import celluloid
fig = plt.figure()
camera = Camera(fig)
for i in range(5):
t = plt.plot(range(i, i + 5))
plt.legend(t, [f'line {i}'])
camera.snap()
animation = camera.animate()
On matplotlib==3.3.4
we get axis ticks accumulating on top of one another (bold / aliased font):
Downgrading to matplotlib==3.2.2
fixes the problem:
The same applies to the titles and labels for all axes.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.