python绘制动态图形是数据可视化更直观、更好看的一种方式,matplotlib工具包是常用的绘图工具,也可以用来绘制动态图形。本文介绍四种绘制动态图形的方法,包括生成图形的代码和动态图形演示示例。
用matplotlib工具包创建动画图有两种方法:
- 使用 pause() 函数
- 使用 FuncAnimation() 函数
代码如下:
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation, writers
import numpy as np
fig = plt.figure(figsize = (7,5))
axes = fig.add_subplot(1,1,1)
axes.set_ylim(0, 300)
palette = ['blue', 'red', 'green',
'darkorange', 'maroon', 'black']
y1, y2, y3, y4, y5, y6 = [], [], [], [], [], []
def animation_function(i):
y1 = i
y2 = 5 * i
y3 = 3 * i
y4 = 2 * i
y5 = 6 * i
y6 = 3 * i
plt.xlabel("Country")
plt.ylabel("GDP of Country")
plt.bar(["India", "China", "Germany",
"USA", "Canada", "UK"],
[y1, y2, y3, y4, y5, y6],
color = palette)
plt.title("Bar Chart Animation")
animation = FuncAnimation(fig, animation_function,
interval = 50)
plt.show()
如下图:

横向柱状跑图 (Horizontal Bar Chart Race),使用FuncAnimation() 函数
以下代码是绘制世界1500年-2018年主要城市人口变化横向柱状跑图,需要数据集文件city_populations.csv评论区留言。
程序代码如下:
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.animation import FuncAnimation
df = pd.read_csv('city_populations.csv',
usecols=['name', 'group', 'year', 'value'])
colors = dict(zip(['India','Europe','Asia',
'Latin America','Middle East',
'North America','Africa'],
['#adb0ff', '#ffb3ff', '#90d595',
'#e48381', '#aafbff', '#f7bb5f',
'#eafb50']))
group_lk = df.set_index('name')['group'].to_dict()
def draw_barchart(year):
dff = df[df['year'].eq(year)].sort_values(by='value',
ascending=True).tail(10)
ax.clear()
ax.barh(dff['name'], dff['value'],
color=[colors[group_lk[x]] for x in dff['name']])
dx = dff['value'].max() / 200
for i, (value, name) in enumerate(zip(dff['value'],
dff['name'])):
ax.text(value-dx, i, name,
size=14, weight=600,
ha='right', va='bottom')
ax.text(value-dx, i-.25, group_lk[name],
size=10, color='#444444',
ha='right', va='baseline')
ax.text(value+dx, i, f'{value:,.0f}',
size=14, ha='left', va='center')
# polished styles
ax.text(1, 0.4, year, transform=ax.transAxes,
color='#777777', size=46, ha='right',
weight=800)
ax.text(0, 1.06, 'Population (thousands)',
transform=ax.transAxes, size=12,
color='#777777')
ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
ax.xaxis.set_ticks_position('top')
ax.tick_params(axis='x', colors='#777777', labelsize=12)
ax.set_yticks([])
ax.margins(0, 0.01)
ax.grid(which='major', axis='x', linestyle='-')
ax.set_axisbelow(True)
ax.text(0, 1.12, 'The most populous cities in the world from 1500 to 2018',
transform=ax.transAxes, size=24, weight=600, ha='left')
ax.text(1, 0, ' ',
transform=ax.transAxes, ha='right', color='#777777',
bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
plt.box(False)
plt.show()
fig, ax = plt.subplots(figsize=(15, 8))
animator = FuncAnimation(fig, draw_barchart,
frames = range(1990, 2019))
plt.show()

散点图动画,使用FuncAnimation()函数
在本例中, 使用random 数据和自定义函数animation_func()
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import random
import numpy as np
x = []
y = []
colors = []
fig = plt.figure(figsize=(7,5))
def animation_func(i):
x.append(random.randint(0,100))
y.append(random.randint(0,100))
colors.append(np.random.rand(1))
area = random.randint(0,30) * random.randint(0,30)
plt.xlim(0,100)
plt.ylim(0,100)
plt.scatter(x, y, c = colors, s = area, alpha = 0.5)
animation = FuncAnimation(fig, animation_func,
interval = 100)
plt.show()
如下图:

使用 pause() 函数绘制动态直线
matplotlib工具包的pyplot模块中有pause()函数,可用来设置时间间隔参数,达到绘制直线的动画效果。
代码如下:
from matplotlib import pyplot as plt
x = []
y = []
for i in range(100):
x.append(i)
y.append(i)
# Mention x and y limits to define their range
plt.xlim(0, 100)
plt.ylim(0, 100)
# Ploting graph
plt.plot(x, y, color = 'green')
plt.pause(0.01)
plt.show()
如下图:

使用 FuncAnimation() 绘制动态直线
FuncAnimation() 函数本身并不能创建动画效果,而是通过生成一系列不同参数的图片来实现动画效果.
Syntax: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, *, cache_frame_data=True, **kwargs)
在这个实例代码中,使用FuncAnimation函数创建一条直线的简单动画效果,只需要调整参数即刻。
from matplotlib import pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
x = []
y = []
figure, ax = plt.subplots()
# Setting limits for x and y axis
ax.set_xlim(0, 100)
ax.set_ylim(0, 12)
# Since plotting a single graph
line, = ax.plot(0, 0)
def animation_function(i):
x.append(i * 15)
y.append(i)
line.set_xdata(x)
line.set_ydata(y)
return line,
animation = FuncAnimation(figure,
func = animation_function,
frames = np.arange(0, 10, 0.1),
interval = 10)
plt.show()
如下图:

发布者:股市刺客,转载请注明出处:https://www.95sca.cn/archives/76347
站内所有文章皆来自网络转载或读者投稿,请勿用于商业用途。如有侵权、不妥之处,请联系站长并出示版权证明以便删除。敬请谅解!