Search code examples
pythonmatplotlibpython-ggplot

How do I use Matplotlib to save an image generated with ggplot?


While this part works

import matplotlib.pyplot as plt
from ggplot import *
import numpy as np
import pandas as pd

df = pd.DataFrame({'Height':np.random.randn(10),
                   'Weight':np.random.randn(10),
                   'Gender': ["Male","Male","Male","Male","Male",
                              "Female","Female","Female","Female","Female"]})
p=ggplot(aes(x='Height', y='Weight', color='Gender'), data=df)  + geom_point()
p.make()
fig = plt.gcf()
ax = plt.gca()
fig.set_figwidth(25, forward=True)
plt.show()

when I try to save the image, it fails miserably generating a blank image.

plt.savefig("image.tiff", dpi=300)

Any ideas? Thanks!


Solution

  • I successfully saved the figure to file using the ggplot object save method. Here is an example:

    p.save('image.tiff', width=12, height=8, dpi=144)
    

    For more info, see the comment by @Johan in this SO response, the source code found here, or the example in the ggplot | docs found here.

    In terms of setting the on screen size, it doesn't seem like it's possible with the current API. A possible hack is to clone the repo and modify line 624 to be the following:

    self.fig, self.subplots = plt.subplots(subplot_kw=subplot_kw, figsize=(my_x, my_y)
    

    where my_x and my_y are the x and y sizes you'd like for the on screen display. Then use the show method:

    p.show()