Python 中的散点图动画:
在这个例子中,我们将使用随机函数在 python 中动画散点图。我们将遍历animation_func并在迭代时绘制 x 和 y 轴的随机值。
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()
输出:
???? 条形图追赶的水平移动:
在这里,我们将使用城市数据集中的最高人口绘制条形图竞赛。
不同的城市会有不同的条形图,条形图追赶将从 1990 年到 2018 年迭代。
我从人口最多的数据集中选择了最高城市的国家。
需要用到的数据集可以从这里下载:city_populations
Python
import pandas as pd import matplotlib.pyplot as plt import matplotlib.ticker as ticker from matplotlib.animation import FuncAnimation plt.rcParams['font.sans-serif'] = ['Microsoft YaHei'] 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') 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, '从 1500 年到 2018 年世界上人口最多的城市', transform=ax.transAxes, size=24, weight=600, ha='left') ax.text(1, 0, 'by haiyong.site | 海拥', 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()
输出: