4

I've imported ggplot into python and am running the following script with the hopes that ggsave() will actually save my plot somewhere, however it does not seem to actually be writing anything to a .png file for use later. The plot is returned when I return it as p in my interpreter, but I'm having to manually save it.

import ggplot

#d as some pandas dataframe

k = [2,3,4,5]

for i in k:
    p = ggplot(d, aes(x='x', y='y', color='cluster'+str(i))) + geom_point(size=75) + ggtitle("Cluster Result: "+str(i))
    file_name = "Clusters_"+str(i)+'.png'  
    #this is not saving to any directory  
    ggsave(p,file=file_name)

This is the output in the interpreter... but no file saved to any directory.

Saving 11.0 x 8.0 in image.
Saving 11.0 x 8.0 in image.
Saving 11.0 x 8.0 in image.
Saving 11.0 x 8.0 in image.
Saving 11.0 x 8.0 in image.
Saving 11.0 x 8.0 in image.
unique_beast
  • 1,379
  • 2
  • 11
  • 23

2 Answers2

5

The reason you can't find your graphs is because they are saved in the current working directory. If you haven't changed anything, that will be your default directory for Python. Call os.getcwd() to get your current directory, and then go there for your graphs. Alternatively you can save everything to a predetermined location by defining a path when calling ggsave.

ggsave(plot = p, filename = file_name, path = "C:\Documents\Graphs")

I would also like to note that User3926962 is close, in regards to naming methods for ggsave, but if you define your parameters with the plot value listed first then you need to also need to specify that p is the plot. The reason you need to do that is because ggsave calls for the filename before calling for the plot, so if you run:

ggsave(p, filename = file_name)

you will get the error:

TypeError: ggsave() got multiple values for argument 'filename'

To fix this simply define your plot:

ggsave(plot = p, filename = file_name)

Source:

ggsave(filename = None, plot = None, device = None, format = None,
               path = None, scale = 1, width = None, height = None, units = "in",
               dpi = 300, limitsize=True, **kwargs)

Link

Peter Maguire
  • 391
  • 4
  • 7
  • 3
    broken link. Looks like ggsave has been removed from `ggplot` for python – Dima Lituiev Jan 12 '17 at 21:39
  • 4
    It has been replaced by a `save()` method on the `ggplot` class: `p.save(filename, width=None, height=None, dpi=180)`. Source: [https://github.com/yhat/ggpy/blob/master/ggplot/ggplot.py#L536](https://github.com/yhat/ggpy/blob/master/ggplot/ggplot.py#L536) – Johan Mar 23 '17 at 08:42
0

The below satisfied saving the filename

ggsave(p,file_name)
unique_beast
  • 1,379
  • 2
  • 11
  • 23