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

问题描述 投票:0回答:1

我最近又回到学习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的动画方面,但是我无法弄清楚如何将所有内容组合在一起以正确和平滑地制作动画。

感谢您帮助我进一步增加自己的爱好。

python python-3.x matplotlib plot graphing
1个回答
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(...)下的所有其他内容

© www.soinside.com 2019 - 2024. All rights reserved.