【python入门项目】在 Python 中创建条形图追赶动画

x33g5p2x  于2021-09-25 转载在 Python  
字(4.3k)|赞(0)|评价(0)|浏览(567)

使用 Matplotlib 创建动画有两种方法:

  • 使用 pause() 函数
  • 使用 FuncAnimation() 函数

🍖 方法一:使用 pause() 函数

在暂停()的matplotlib库的pyplot模块在功能上用于暂停为参数提到间隔秒。考虑下面的示例,我们将使用 matplotlib 创建一个简单的线性图并在其中显示动画:

创建 2 个数组 X 和 Y,并存储从 1 到 100 的值。
使用 plot() 函数绘制 X 和 Y。
以合适的时间间隔添加 pause() 函数
运行程序,你会看到动画。

Python

  1. from matplotlib import pyplot as plt
  2. x = []
  3. y = []
  4. for i in range(100):
  5. x.append(i)
  6. y.append(i)
  7. # 提及 x 和 y 限制以定义其范围
  8. plt.xlim(0, 100)
  9. plt.ylim(0, 100)
  10. # 绘制图形
  11. plt.plot(x, y, color = 'green')
  12. plt.pause(0.01)
  13. plt.show()

输出 :

同样,你也可以使用 pause() 函数在各种绘图中创建动画。

🚀 方法二:使用 FuncAnimation() 函数

这个FuncAnimation() 函数不会自己创建动画,而是从我们传递的一系列图形中创建动画。
语法: FuncAnimation(figure, animation_function, frames=None, init_func=None, fargs=None, save_count=None, /, cache_frame_data=True,
/
/*kwargs)

现在您可以使用 FuncAnimation 函数制作多种类型的动画:

🥋 线性图动画:

在这个例子中,我们将创建一个简单的线性图,它将显示一条线的动画。同样,使用 FuncAnimation,我们可以创建多种类型的动画视觉表示。我们只需要在一个函数中定义我们的动画,然后用合适的参数将它传递给FuncAnimation。

Python

  1. from matplotlib import pyplot as plt
  2. from matplotlib.animation import FuncAnimation
  3. import numpy as np
  4. x = []
  5. y = []
  6. figure, ax = plt.subplots()
  7. # 设置 x 和 y 轴的限制
  8. ax.set_xlim(0, 100)
  9. ax.set_ylim(0, 12)
  10. # 绘制单个图形
  11. line, = ax.plot(0, 0)
  12. def animation_function(i):
  13. x.append(i * 15)
  14. y.append(i)
  15. line.set_xdata(x)
  16. line.set_ydata(y)
  17. return line,
  18. animation = FuncAnimation(figure,
  19. func = animation_function,
  20. frames = np.arange(0, 10, 0.1),
  21. interval = 10)
  22. plt.show()

输出:

🎻 Python 中的条形图追赶动画

在此示例中,我们将创建一个简单的条形图动画,它将显示每个条形的动画。

Python

  1. from matplotlib import pyplot as plt
  2. from matplotlib.animation import FuncAnimation, writers
  3. import numpy as np
  4. plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
  5. fig = plt.figure(figsize = (7,5))
  6. axes = fig.add_subplot(1,1,1)
  7. axes.set_ylim(0, 300)
  8. palette = ['blue', 'red', 'green',
  9. 'darkorange', 'maroon', 'black']
  10. y1, y2, y3, y4, y5, y6 = [], [], [], [], [], []
  11. def animation_function(i):
  12. y1 = i
  13. y2 = 6 * i
  14. y3 = 3 * i
  15. y4 = 2 * i
  16. y5 = 5 * i
  17. y6 = 3 * i
  18. plt.xlabel("国家")
  19. plt.ylabel("国家GDP")
  20. plt.bar(["印度", "中国", "德国",
  21. "美国", "加拿大", "英国"],
  22. [y1, y2, y3, y4, y5, y6],
  23. color = palette)
  24. plt.title("条形图动画")
  25. animation = FuncAnimation(fig, animation_function,
  26. interval = 50)
  27. plt.show()

输出:

🌌 Python 中的散点图动画:

在这个例子中,我们将使用随机函数在 python 中动画散点图。我们将遍历animation_func并在迭代时绘制 x 和 y 轴的随机值。

  1. from matplotlib import pyplot as plt
  2. from matplotlib.animation import FuncAnimation
  3. import random
  4. import numpy as np
  5. x = []
  6. y = []
  7. colors = []
  8. fig = plt.figure(figsize=(7,5))
  9. def animation_func(i):
  10. x.append(random.randint(0,100))
  11. y.append(random.randint(0,100))
  12. colors.append(np.random.rand(1))
  13. area = random.randint(0,30) * random.randint(0,30)
  14. plt.xlim(0,100)
  15. plt.ylim(0,100)
  16. plt.scatter(x, y, c = colors, s = area, alpha = 0.5)
  17. animation = FuncAnimation(fig, animation_func,
  18. interval = 100)
  19. plt.show()

输出:

🛹 条形图追赶的水平移动:

在这里,我们将使用城市数据集中的最高人口绘制条形图竞赛。
不同的城市会有不同的条形图,条形图追赶将从 1990 年到 2018 年迭代。
我从人口最多的数据集中选择了最高城市的国家。
需要用到的数据集可以从这里下载:city_populations

Python

  1. import pandas as pd
  2. import matplotlib.pyplot as plt
  3. import matplotlib.ticker as ticker
  4. from matplotlib.animation import FuncAnimation
  5. plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']
  6. df = pd.read_csv('city_populations.csv',
  7. usecols=['name', 'group', 'year', 'value'])
  8. colors = dict(zip(['India','Europe','Asia',
  9. 'Latin America','Middle East',
  10. 'North America','Africa'],
  11. ['#adb0ff', '#ffb3ff', '#90d595',
  12. '#e48381', '#aafbff', '#f7bb5f',
  13. '#eafb50']))
  14. group_lk = df.set_index('name')['group'].to_dict()
  15. def draw_barchart(year):
  16. dff = df[df['year'].eq(year)].sort_values(by='value',
  17. ascending=True).tail(10)
  18. ax.clear()
  19. ax.barh(dff['name'], dff['value'],
  20. color=[colors[group_lk[x]] for x in dff['name']])
  21. dx = dff['value'].max() / 200
  22. for i, (value, name) in enumerate(zip(dff['value'],
  23. dff['name'])):
  24. ax.text(value-dx, i, name,
  25. size=14, weight=600,
  26. ha='right', va='bottom')
  27. ax.text(value-dx, i-.25, group_lk[name],
  28. size=10, color='#444444',
  29. ha='right', va='baseline')
  30. ax.text(value+dx, i, f'{value:,.0f}',
  31. size=14, ha='left', va='center')
  32. ax.text(1, 0.4, year, transform=ax.transAxes,
  33. color='#777777', size=46, ha='right',
  34. weight=800)
  35. ax.text(0, 1.06, 'Population (thousands)',
  36. transform=ax.transAxes, size=12,
  37. color='#777777')
  38. ax.xaxis.set_major_formatter(ticker.StrMethodFormatter('{x:,.0f}'))
  39. ax.xaxis.set_ticks_position('top')
  40. ax.tick_params(axis='x', colors='#777777', labelsize=12)
  41. ax.set_yticks([])
  42. ax.margins(0, 0.01)
  43. ax.grid(which='major', axis='x', linestyle='-')
  44. ax.set_axisbelow(True)
  45. ax.text(0, 1.12, '从 1500 年到 2018 年世界上人口最多的城市',
  46. transform=ax.transAxes, size=24, weight=600, ha='left')
  47. ax.text(1, 0, 'by haiyong.site | 海拥',
  48. transform=ax.transAxes, ha='right', color='#777777',
  49. bbox=dict(facecolor='white', alpha=0.8, edgecolor='white'))
  50. plt.box(False)
  51. plt.show()
  52. fig, ax = plt.subplots(figsize=(15, 8))
  53. animator = FuncAnimation(fig, draw_barchart,
  54. frames = range(1990, 2019))
  55. plt.show()

输出:

相关文章