0

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)

bharatk
  • 4,202
  • 5
  • 16
  • 30
Liam
  • 51
  • 1
  • 4
  • 1
    Replace `plt.savefig(str(item))` by `plt.savefig(str(item) + '.jpg')` for example. The problem is due to saving the images with unknown extensions – singrium Aug 02 '19 at 09:22
  • I have tried this previously however the savefig reads my item as the dataframe and not the string of the variable (apples, bananas). – Liam Aug 02 '19 at 09:37
  • What do you get as a return after you tried it? – singrium Aug 02 '19 at 09:38
  • File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 1966, in save fp = builtins.open(filename, "w+b") FileNotFoundError: [Errno 2] No such file or directory: ' Timetag [UTC] UTMposMeasN1 [] ... pitch1 [°] heave1 [m]\n6892822 2018-12-21 13:28:01 10014875.49 – Liam Aug 02 '19 at 09:39
  • ^ the savefig is trying to save using my dataframe itself and not the name of the variable which is what i would like (apples bananas) – Liam Aug 02 '19 at 09:39
  • Then, you should loop over the dataframes you have (apples and bananas) to get the filenames from them then save your images. Useful [link](https://stackoverflow.com/questions/7837722/what-is-the-most-efficient-way-to-loop-through-dataframes-with-pandas) – singrium Aug 02 '19 at 09:42
  • Not sure that looping through my filenames would correlate correctly with my dataframes. Unless you have a loop in mind. Is there a way i can directly infer the list index string name? – Liam Aug 02 '19 at 09:49
  • I edited my answer (2nd time), please try what I suggested and tell me about the results. – singrium Aug 02 '19 at 10:29

1 Answers1

1

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()
singrium
  • 2,746
  • 5
  • 32
  • 45