如何将带有子图的代码修改为实时动画?



我最近又开始学习python,因为它使用matplotlib和很好地绘制数据的能力。

我决定给自己一个基本项目来绘制两个可视化。第一个是六面骰子上每个面的总滚动,以条形图的形式出现。

第二个图是一个简单的散点图,显示滚动的每个面的滚动。这意味着,它将显示负责第一个绘图的卷的输出。

到目前为止,我做到了这一点,并取得了不错的结果,但是,我想在两个情节上对每个滚动进行动画处理,但到目前为止,这是我遇到很多麻烦的事情。

目前,我的基本代码如下:

import random 
import matplotlib.pyplot as plt
# Generate a plot displaying two elements:
# One: Display 6 side die roll results
# Two: Plot the order of rolls
numRolls = 100
rollTotals = [0, 0, 0, 0, 0, 0]
rollSeq = []
for roll in range(numRolls):
currentRoll = random.randint(1, 6)
rollTotals[currentRoll - 1] += 1
rollSeq.append(currentRoll)
plt.subplot(2, 1, 1)
plt.bar([1, 2, 3, 4, 5, 6], rollTotals, 1/1.5)
plt.title("Roll Totals")
plt.subplot(2, 1, 2)
plt.plot(rollSeq)
plt.title("Roll Sequence")
plt.show()

numRolls是一个常量,允许快速可变地更改掷骰子的数量。rollTotals是一个 6 元素的值列表,用于表示骰子每侧的辊总数。rollSeq是一个列表,用于显示每个卷的顺序。

如您所见,我有一个基本脚本可以立即模拟结果并将其输出为子图。我已经研究了matplotlib的动画方面,但我无法弄清楚如何准确地将所有内容结合在一起以正确流畅地制作动画。

感谢您帮助我进一步发展我的爱好。

在浏览了 20 个不同的帖子并重新阅读文档至少 10 次之后,我想出了这个:

import random
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# Generate a plot displaying two elements:
# One: Display 6 side die roll results
# Two: Plot the order of rolls
numRolls = 300
rollTotals = [0, 0, 0, 0, 0, 0]
rollSeq = []
# Create a figure with two subplots
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax2 = fig.add_subplot(2,1,2)
# Adjust spacing between plots
plt.subplots_adjust(top = 0.93, bottom = 0.07, hspace = 0.3)
#define the function for use in matplotlib.animation.funcAnimation
def animate(i):
currentRoll = random.randint(1, 6)
rollTotals[currentRoll - 1] += 1
rollSeq.append(currentRoll)
# Set subplot data
ax1.clear()
ax1.bar([1, 2, 3, 4, 5, 6], rollTotals, 1/1.5)
ax2.clear()
ax2.plot(rollSeq)
xlim = len(rollSeq)
ax2.set_xlim(xlim - 30, xlim)
# Set subplot titles
ax1.set_title("Roll Totals")
ax2.set_title("Roll Sequence")

ani = animation.FuncAnimation(fig, animate, frames=numRolls, interval=50, repeat=False)
# Set up formatting for the movie files
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
# Save ani
ani.save(r'D:_DataDesktopAnimationOutput.mp4', writer=writer)
#plt.show()

这可以通过在animation.FuncAnimation中使用闪电来优化,但它更令人困惑。事实上,这可能可以进一步优化。另外,我想出了如何将动画另存为mp4。

如果您不想导出,请取消注释plt.show()并删除"ani = animation.FuncAnimation(...)

最新更新