python - 如何将列表变量传递给 matplotlib plt.savefig 参数
问题描述
我有一个 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()
文件“”,第 17 行,在 plt.savefig(str(item))
文件“C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\pyplot.py”,第 689 行,在 savefig res = fig.savefig(*args, **kwargs)
文件“C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py”,第 2094 行,在 savefig self.canvas.print_figure(fname, **kwargs)
文件“C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backend_bases.py”,第 2006 行,在 print_figure canvas = self._get_output_canvas(format)
文件“C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\backend_bases.py”,第 1948 行,在 _get_output_canvas .format(fmt, ", ".join(sorted(self.get_supported_filetypes()))))
ValueError:不支持格式“027619\n\n[19920 行 x 15 列]”(支持的格式:eps、jpeg、jpg、pdf、pgf、png、ps、raw、rgba、svg、svgz、tif、tiff)
解决方案
根据您收到的错误,问题是由于保存了未知扩展名的图像。
因此,只需将扩展名 ('jpg', 'png', ...) 添加到plt.savefig(str(item))
, 即可解决问题plt.savefig(str(item) + '.jpg')
。
编辑:
由于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()
推荐阅读
- android - 在 textView 上显示图像位置
- javascript - 在 vscode 语言服务器中预打开文件
- python - CSV 中的 Snowflake COPY INTO 列
- ssas - 使用 DAX 实施 SSAS RLS
- scala - Scala元组添加保持序列相同的顺序
- javascript - 通过 jQuery(或类似方法)使用 timeAgo 来显示用户(客户端)进入或刷新页面的时间
- swift - 尝试通过许多 UITextView 打印 NSAttributedString 会导致崩溃
- c# - 成员无法识别或无法访问 WPF
- php - 在没有安全标志的情况下创建的 Cookie XSRF-TOKEN - Laravel 5.8
- angular - ng-bootstrap ngbDatepicker 显示为 ng-template 模态