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

时间:2019-04-03 00:25:19

标签: python python-3.x matplotlib plot graphing

我最近因使用matplotlib并能够很好地绘制数据而重新学习python。

我决定给自己一个基础项目,以绘制两个可视化图像。首先是条形图形式的六面模具上每个面的总滚动。

第二个图将是一个简单的散点图,显示每个滚动面的滚动。意思是,它将显示负责第一个情节的掷骰的输出。

到目前为止,我设法做到了这一点,并取得了不错的成绩,但是,我想为每张图都制作动画,但这是我迄今为止遇到的很多麻烦。

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

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的动画方面,但是我无法弄清楚如何正确地将所有内容组合在一起以正确流畅地制作动画。

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

1 个答案:

答案 0 :(得分:0)

浏览了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:\_Data\Desktop\AnimationOutput.mp4', writer=writer)

#plt.show()

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

如果您不想导出,请取消注释plt.show()并删除ani = animation.FuncAnimation(...)下的所有其他内容