如何使用 Matplotlib 保存使用 ggplot 生成的图像?

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

虽然这部分有效

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()

当我尝试保存图像时,它不幸地生成了一张空白图像,但失败了。

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

有什么想法吗?谢谢!

你试过 ggsave(plot = p, filename = 'image.tiff') 还是 p.save('image.tiff')

编辑 ggsave 已从 ggplot 中删除,请改用第二种解决方案。

我使用 ggplot 对象 save 方法成功地将图形保存到文件中。这是一个例子:

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

有关详细信息,请参阅@Johan 在 SO response, the source code found here, or the example in the ggplot | docs found here 中的评论。

在设置屏幕尺寸方面,目前的 API 似乎无法实现。一个可能的破解方法是克隆 repo 并将 line 624 修改为以下内容:

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

其中 my_x 和 my_y 是您希望在屏幕上显示的 x 和 y 尺寸。然后使用show方法:

p.show()

感谢所有评论 - 这就是最终的工作。代码中有一点重复,但终于成功了。

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()

w,h=25,10 #set width and height for both screen and file size

#this part prints on screen the chart
fig.set_figwidth(w, forward=True)  #screen
fig.set_figheight(h, forward=True) #screen
plt.show()

#this part saves it to file
p.save(filename, width=w, height=h, dpi=300) #file