【问题标题】:Python: Loop through a dataframe and create one plot for each datapointPython:遍历数据框并为每个数据点创建一个图
【发布时间】:2018-09-24 12:28:24
【问题描述】:

以下代码生成折线图。这里 x 轴是通用的,y 轴分为两个(y1 和 y2),它们是针对 x 绘制的。我正在使用 savefig() 将绘图保存为 .PNG 文件。

现在,我需要在每个数据点(或为每个 x 值)生成图像,这样这些图像就像原始图形的框架一样。我尝试使用 'Iterrows' 循环遍历数据框。但是,这并没有解决。

PS:我打算使用这些生成的帧通过 ffmpeg 转换成视频。 Animate() 在这里不符合我的目的,因此不使用它。快速帮助将不胜感激。

提前致谢!

def MakeLineGraph(stats,title, savegraph) :

x = stats[stats.columns[1]]
y1 = stats[stats.columns[2]]
y2 = stats[stats.columns[3]]
xlab = list(stats)[1]
ylab = list(stats)[0]

fig = plt.figure()
pli = plt.subplot()

pli.plot(x, y1, color='g', linewidth=5.0, label='label1')
pli.plot(x, y2, color='y', linewidth=5.0, label='label2')

plt.xlabel(xlab)
plt.ylabel(ylab)
plt.title(title)

# Removing the plot frame lines.
ax = plt.subplot(111)
ax.spines["top"].set_visible(False)
ax.spines["bottom"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.spines["left"].set_visible(False)

ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()

leg = plt.legend()

for line in leg.get_lines():
    line.set_linewidth(6)

if len(x) < 25:
    pli.xticks(x.tolist())

plt.show()

if (savegraph == True):
    fig.set_size_inches((19.2, 10.8))
    fig.savefig(image_folder + 'Progress.png', transparent=True, dpi=600)

【问题讨论】:

  • 我建议将其重写为一个函数,该函数采用 one 数据点并制作 one 绘图,并使用 df.apply(.. ., axis=1) (即使这很慢)。然后,您可以收集帧并制作动画。
  • matplotlib.animation 正是为此目的而编写的。您只需要创建一次图形和轴,然后只需在 FuncAnimation 重复调用的函数中更改数据。

标签: python python-3.x pandas dataframe matplotlib


【解决方案1】:

感谢您的意见。 我稍微修改了代码解决了这个问题。需要注意的是,我只是分享核心部分,格式和上面一样。

def MakeLineGraph(stats,title, savegraph) :

x = stats[stats.columns[1]]
y1 = stats[stats.columns[2]]
y2 = stats[stats.columns[3]]
xlab = list(stats)[1]
ylab = list(stats)[0]

fig, pli = plt.subplots()

pli = plt.subplot()
pli.imshow(pltimg, extent=[0, 95, 0, 55])

line, = pli.plot(x, y1, color='g', linewidth=5.0, label='label1')
for n in range(len(x)):
    line.set_data(x[:n], y1[:n])
    fig.canvas.draw()
    fig.savefig('./frames/Frame%03d.png' % n)

line, = pli.plot(x, y2, color='y', linewidth=5.0, label='label2')
for n in range(len(x)):
    line.set_data(x[:n], y2[:n])
    fig.canvas.draw()
    fig.savefig('./frames/Frame%03d.png' % n)

【讨论】:

    猜你喜欢
    • 2017-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多