Reputation: 51
I have a for loop that saves a plot at each cycle. I would like the string name of my list, to be the savefig filename. However, Savefig requires a filename path or filename + format.
I am struggling to pass my listed variable string as a filename. Savefig infers the dataframe itself instead of the string name. Suggestions to overcome much appreciated.
Ultimately i would like my graphs to be named apples and bananas (See below).
I have tried below methods within my for loop however all returned error.
#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)
Upvotes: 0
Views: 3893
Reputation: 3016
According to the error you got, the problem is due to saving the images with unknown extensions.
So the problem can be fixed by simply adding an extension ('jpg', 'png', ...) to plt.savefig(str(item))
, to be plt.savefig(str(item) + '.jpg')
.
EDIT:
Since the list_to_plot
contains dataframes and based to what we discussed on the comment, I suggest the following:
Create another list with the dataframes names, then the solution would be as following:
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()
Upvotes: 1