首页 > 解决方案 > Python:遍历数据框并为每个数据点创建一个图

问题描述

下面的代码生成一个线图。这里 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)

标签: pythonpython-3.xpandasdataframematplotlib

解决方案


感谢您的输入。我稍微修改了代码解决了这个问题。需要注意的是,我只是分享核心部分,格式与上面相同。

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)

推荐阅读