English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
This article describes the method of implementing the animation effect of the raindrop diagram using Matplotlib in Python. Shared for everyone's reference, as follows:
Key points
win10Install ffmpeg
Using the animation function
update function
win10Install ffmpeg
Because the animation image needs to be saved as .mp4Format, it needs to use ffmpeg, download it from the official website, I downloaded the windows version64bit static version, unzip it to the commonly used path of software installation, and add the ffmpeg path to the environment variable (this method is not used at the end, but it is still added)
animationa function
To be precise, it is the animation.FuncAnimation function
Common parameters:
animation.FuncAnimation(fig, func, frames, init_func, interval)
fig: matplotlib.figure.Figure
func: Each frame is called, and the first parameter of the function is the value in the next parameter frames
frames: iterable, can be an integer, if an integer is passed, it is equivalent to passing range(frames)
init_func: Initialization function, which is the initial setting of fig
interval: Delay between frames in milliseconds. Defaults to 200.
update function
This function involves the changes in parameters of the graphics drawn in each frame, such as the size, color, and position of the raindrops in the example routine (scatter plot drawing), for details, see the code
program implementation
Initially found the routine based on the BSD protocol and after some modifications of my own, so I also stick to the protocol in the code
# ----------------------------------------------------------------------------- # Copyright (c) 2015, Nicolas P. Rougier. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- import numpy as np import matplotlib import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from matplotlib import animation import os # Determine the location of ffmpeg.exe, tried adding it to the environment variables but still prompted that MovieWriter could not be found, and this method finally solved it in Python2.7version path name needs to declare the encoding as unicode in Python3whether there is any, this is2.X and3.x version has a difference in encoding plt.rcParams['animation.ffmpeg_path'] = u"D:\\Applications\\ffmpeg-20170503-a75ef15-win64-static\\bin\\ffmpeg.exe # Here change the current working directory to facilitate automatic saving of files to this path below os.chdir("d:\\Files\\python\\matplotlib") # No toolbar matplotlib.rcParams['toolbar'] = 'None' # New figure with white background fig = plt.figure(figsize=(6,6), facecolor='white') # New axis over the whole figure and a 1:1 aspect ratio # ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1) ax = fig.add_axes([0.005,0.005,0.990,0.990], frameon=True, aspect=1) # Number of ring n = 50 size_min = 50 size_max = 50*50 # Ring position, the position of the ring, the range is [0,1] among P = np.random.uniform(0,1,(n,2)) # Ring colors, the color of the ring C = np.ones((n,4)) * (0,1,0,1) # C = np.ones((n,3)) * (1,0,1) # The alpha color channel goes from 0 (transparent) to 1 (opaque) # Transparency, the value is between [0,1] among C[:,2] = np.linspace(0,1,n) # Ring sizes, the range is [50,2500] S = np.linspace(size_min, size_max, n) # Scatter plot # Scatter plot drawing scat = ax.scatter(P[:,0], P[:,1], s=S, lw = 0.5, edgecolors = C, facecolors='None') # Ensure limits are [0,1] and remove ticks # Ensure x, y range is within [0,1] between, remove axis ticks ), ax.set_xlim(0,1), ax.set_xticks([]) ), ax.set_ylim(0,1), ax.set_yticks([]) def update(frame): global P, C, S # Every ring is made more transparent, each ring becomes more transparent C[:,3] = np.maximum(0, C[:,3] - 1.0/n) # Each ring is made larger, each ring is larger than the original S += (size_max - size_min) / n # Reset ring specific ring (relative to frame number) i = frame % 50 P[i] = np.random.uniform(0,1,2) # P[i] = P[i,:], modifying the values of x and y positions at the same time S[i] = size_min # Start from the smallest shape C[i,3] = 1 # Set transparency to1 # Update scatter object # Update scatter plot object properties, such as edgecolors, sizes, offsets, etc. scat.set_edgecolors(C) #set edge color scat.set_sizes(S) #set size scat.set_offsets(P) #set offset return scat, animate = FuncAnimation(fig, update, frames = 300, interval=70)#interval is every70 milliseconds update once, you can view help FFwriter = animation.FFMpegWriter(fps=20) #frames per second frame per second animate.save('rain.mp4', writer=FFwriter, dpi=360) Set resolution plt.show()
The generated is mp4I converted it into a very small gif and showed the effect, but it seems that the format of saving as gif is not good
Readers who are interested in more content related to Python can check the special topics on this site: 'Python Data Structures and Algorithms Tutorial', 'Summary of Python Function Usage Skills', 'Summary of Python String Operation Skills', 'Classic Tutorial of Python入门与进阶', and 'Summary of Python File and Directory Operation Skills'.
I hope the content described in this article will be helpful to everyone's Python program design.
Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email for reporting, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)