循环中plt.savefig出错

时间:2017-02-03 12:12:08

标签: python python-3.x pandas matplotlib

首先,我必须说我是Python的真正初学者(以及编程本身)所以这可能是一个愚蠢的问题,但我无法找到解决方案。

我从3个不同的.csv文件加载数据,然后进行一些计算,最后我想保存3个热图。我的问题在于储蓄。当我使用plt.savefig('whatever.jpg')时,它显然只保存循环中的最后一个热图。我尝试将其更改为plt.savefig('{}.jpg'.format(i)),但我收到了错误,而且我不知道如何修复。我会感激任何提示! (来自Anaconda的Python 3)

import seaborn as sns
import pandas as pd 
import matplotlib.pyplot as plt
%matplotlib inline

instrumenty = ['gold','sp500','dax']

for i in instrumenty:

    i = pd.read_csv(i+'_m.csv', sep=',')
    i['Miesiąc'] = pd.DatetimeIndex(i['Data']).month
    i['Rok'] = pd.DatetimeIndex(i['Data']).year
    i['Zmiana']=i['Zamkniecie'].pct_change()
    i_pt = i[1:].pivot_table(index='Rok',columns='Miesiąc',values='Zmiana')
    sns.heatmap(i_pt, linewidths=1, cmap='PiYG')
    plt.savefig('{}.png'.format(i))
    plt.clf()

错误:

   FileNotFoundError                         Traceback (most recent call last)
<ipython-input-30-5729b6a0480f> in <module>()
     14     i_pt = i[1:].pivot_table(index='Rok',columns='Miesiąc',values='Zmiana')
     15     sns.heatmap(i_pt, linewidths=1, cmap='PiYG')
---> 16     plt.savefig('{}.png'.format(i))
     17     plt.clf()
     18 

C:\Users\user\Anaconda3\lib\site-packages\matplotlib\pyplot.py in savefig(*args, **kwargs)
    694 def savefig(*args, **kwargs):
    695     fig = gcf()
--> 696     res = fig.savefig(*args, **kwargs)
    697     fig.canvas.draw_idle()   # need this if 'transparent=True' to reset colors
    698     return res

C:\Users\user\Anaconda3\lib\site-packages\matplotlib\figure.py in savefig(self, *args, **kwargs)
   1561             self.set_frameon(frameon)
   1562 
-> 1563         self.canvas.print_figure(*args, **kwargs)
   1564 
   1565         if frameon:

C:\Users\user\Anaconda3\lib\site-packages\matplotlib\backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, **kwargs)
   2230                 orientation=orientation,
   2231                 bbox_inches_restore=_bbox_inches_restore,
-> 2232                 **kwargs)
   2233         finally:
   2234             if bbox_inches and restore_bbox:

C:\Users\user\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
    530         renderer.dpi = self.figure.dpi
    531         if is_string_like(filename_or_obj):
--> 532             filename_or_obj = open(filename_or_obj, 'wb')
    533             close = True
    534         else:

即使没有plt.savefig我也做错了,因为结果是one strange chart with 3 legends而不是3个图表。

2 个答案:

答案 0 :(得分:3)

您在此处覆盖i

instrumenty = ['gold','sp500','dax']
for i in instrumenty:
    i = pd.read_csv(i+'_m.csv', sep=',')

更好地使用name

for name in instrumenty:
    # use `name`
    i = pd.read_csv(name +'_m.csv', sep=',')
    i['Miesiąc'] = pd.DatetimeIndex(i['Data']).month
    i['Rok'] = pd.DatetimeIndex(i['Data']).year
    i['Zmiana']=i['Zamkniecie'].pct_change()
    i_pt = i[1:].pivot_table(index='Rok',columns='Miesiąc',values='Zmiana')
    sns.heatmap(i_pt, linewidths=1, cmap='PiYG')
    plt.savefig('{}.png'.format(name))
    plt.clf()

这是重要的部分:

plt.savefig('{}.png'.format(name))

答案 1 :(得分:0)

对我来说,主要问题是我忘记放置文件的扩展名.png

定义后:

plot_filename = 'plot_'+filename

以下无效

plt.savefig(str(plot_filename))
# or this neither
plt.savefig(plot_filename))

但以下可以完成

plt.savefig("{}.png".format(plot_filename))