如何将列表变量传递到matplotlib保存图阿古门

2024-10-01 07:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个for循环,它在每个周期保存一个绘图。我希望我的列表的字符串名是savefig文件名。但是,Savefig需要文件名路径或文件名+格式。

我正在努力将列出的变量字符串作为文件名传递。Savefig推断数据帧本身而不是字符串名称。建议克服非常感谢。

最后,我希望我的图表命名为苹果和香蕉(见下文)。

我在for循环中尝试了以下方法,但是都返回了错误。

#plt.savefig(str(item))
#plt.savefig("Graph" + str(item) +".png", format="PNG")
#plt.savefig('Graph_{}.png'.format(item))   
#plt.savefig(item, format='.jpg')

apples = df_final[(df_final['Timetag [UTC]'] > '21/12/2018  13:28:00') & 
(df_final['Timetag [UTC]'] <= '21/12/2018  19:00:00')]

bananas = df_final[(df_final['Timetag [UTC]'] > '21/12/2018  17:28:00') & 
(df_final['Timetag [UTC]'] <= '21/12/2018  21:00:00')]


List_to_plot = [apples, bananas]


for item in List_to_plot:
    item.plot(y='Delta Port/STBD', label='Sway')
    plt.savefig(str(item))
    plt.show()
    plt.clf()

File "", line 17, in plt.savefig(str(item))

File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 689, in savefig res = fig.savefig(*args, **kwargs)

File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py", line 2094, in savefig self.canvas.print_figure(fname, **kwargs)

File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 2006, in print_figure canvas = self._get_output_canvas(format)

File "C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 1948, in _get_output_canvas .format(fmt, ", ".join(sorted(self.get_supported_filetypes()))))

ValueError: Format '027619\n\n[19920 rows x 15 columns]' is not supported (supported formats: eps, jpeg, jpg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff)


Tags: informatdf文件名linepltitemfile
1条回答
网友
1楼 · 发布于 2024-10-01 07:24:16

根据您得到的错误,问题是由于保存了具有未知扩展名的图像。
因此,只需在plt.savefig(str(item))中添加一个扩展名('jpg','png',…)就可以解决这个问题了。在

编辑:
由于list_to_plot包含数据帧,并且根据我们在评论中讨论的内容,我建议如下:
用数据帧名称创建另一个列表,则解决方案如下:

List_to_plot = [apples, bananas]
names = ['apples', 'bananas']
# loop over the element in the list_to_plot
for elt in (0, 1):
    # loop over the length of each dataframe to get the index of the image
    for i in range(list_to_plot[elt].shape[0]):
        # do your processing
        item.plot(y='Delta Port/STBD', label='Sway')
        # save the image with the appropriate index
        plt.savefig(names[elt] + '{}.jpg'.format(i))
        plt.show()
        plt.clf()

相关问题 更多 >