使用matplotlib的savefig保存从python pandas生成的图(AxesSubPlot)

时间:2013-10-24 01:55:50

标签: python matplotlib pandas

我正在使用pandas从数据框生成一个图,我想将其保存到文件中:

dtf = pd.DataFrame.from_records(d,columns=h)
fig = plt.figure()
ax = dtf2.plot()
ax = fig.add_subplot(ax)
fig.savefig('~/Documents/output.png')

似乎最后一行,使用matplotlib的savefig,应该可以解决问题。但该代码会产生以下错误:

Traceback (most recent call last):
  File "./testgraph.py", line 76, in <module>
    ax = fig.add_subplot(ax)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 890, in add_subplot
    assert(a.get_figure() is self)
AssertionError

或者,尝试直接在绘图上调用savefig也会出错:

dtf2.plot().savefig('~/Documents/output.png')


  File "./testgraph.py", line 79, in <module>
    dtf2.plot().savefig('~/Documents/output.png')
AttributeError: 'AxesSubplot' object has no attribute 'savefig'

我想我需要以某种方式将plot()返回的子图添加到图中以便使用savefig。我也想知道这是否与AxesSubPlot类背后的magic有关。

编辑:

以下作品(没有引起任何错误),但留下了空白页面图片......

fig = plt.figure()
dtf2.plot()
fig.savefig('output.png')

6 个答案:

答案 0 :(得分:83)

在V 0.14中不推荐使用gcf方法,以下代码适用于我:

plot = dtf.plot()
fig = plot.get_figure()
fig.savefig("output.png")

答案 1 :(得分:12)

所以我不完全确定为什么会这样,但它会用我的情节保存图像:

dtf = pd.DataFrame.from_records(d,columns=h)
dtf2.plot()
fig = plt.gcf()
fig.savefig('output.png')

我猜我原始帖子的最后一个片段保存为空白,因为这个数字永远不会得到熊猫生成的轴。使用上面的代码,通过gcf()调用(获取当前数字)从一些神奇的全局状态返回figure对象,该对象自动烘焙在上面的行中绘制的轴。

答案 2 :(得分:11)

您可以使用implementation 'com.google.code.gson:gson:2.8.6' ,如对问题的评论所建议:

ax.figure.savefig()

如其他答案中所建议的那样,这与import pandas as pd df = pd.DataFrame([0, 1]) ax = df.plot.line() ax.figure.savefig('demo-file.pdf') 相比并没有实际的好处,因此您可以选择最美观的选项。实际上,get_figure() simply returns self.figure

ax.get_figure().savefig()

答案 3 :(得分:6)

Entry函数之后使用plt.savefig()函数似乎很容易:

plot()

答案 4 :(得分:2)

  • 其他答案涉及将情节保存为单个情节,而不是子情节。
  • 在有子图的情况下,图 API 返回 matplotlib.axes.Axesnumpy.ndarray
import pandas as pd
import seaborn as sns  # for sample data
import matplotlib.pyplot as plt

# load data
df = sns.load_dataset('iris')

# display(df.head())
   sepal_length  sepal_width  petal_length  petal_width species
0           5.1          3.5           1.4          0.2  setosa
1           4.9          3.0           1.4          0.2  setosa
2           4.7          3.2           1.3          0.2  setosa
3           4.6          3.1           1.5          0.2  setosa
4           5.0          3.6           1.4          0.2  setosa

使用 pandas.DataFrame.plot() 绘图

  • 以下示例使用 kind='hist',但在指定 'hist' 以外的其他内容时是相同的解决方案
  • 使用 [0] 从数组中获取 axes 之一,并使用 .get_figure() 提取图形。
fig = df.plot(kind='hist', subplots=True, figsize=(6, 6))[0].get_figure()
plt.tight_layout()
fig.savefig('test.png')

enter image description here

使用 pandas.DataFrame.hist() 绘图

1:

  • 在本例中,我们将 df.hist 分配给使用 Axes 创建的 plt.subplots,并保存该 fig
  • 41 分别用于 nrowsncols,但也可以使用其他配置,例如 2 和 {{1} }.
2

enter image description here

2:

  • 使用 fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(6, 6)) df.hist(ax=ax) plt.tight_layout() fig.savefig('test.png') 来展平 .ravel() 的数组
Axes

enter image description here

答案 5 :(得分:0)

这可能是一种更简单的方法:

  

(DesiredFigure).get_figure()。savefig('figure_name.png')

dfcorr.hist(bins=50).get_figure().savefig('correlation_histogram.png')