简体   繁体   English

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

[英]Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

I'm using pandas to generate a plot from a dataframe, which I would like to save to a file:我正在使用 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')

It seems like the last line, using matplotlib's savefig, should do the trick.似乎最后一行,使用 matplotlib 的 savefig,应该可以解决问题。 But that code produces the following error:但该代码产生以下错误:

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

Alternatively, trying to call savefig directly on the plot also errors out:或者,尝试直接在绘图上调用 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'

I think I need to somehow add the subplot returned by plot() to a figure in order to use savefig.我想我需要以某种方式将 plot() 返回的子图添加到图形中才能使用 savefig。 I also wonder if perhaps this has to do with the magic behind the AxesSubPlot class.我还想知道这是否与 AxesSubPlot 类背后的魔法有关。

EDIT:编辑:

the following works (raising no error), but leaves me with a blank page image....以下工作(没有引起错误),但给我留下了一个空白页面图像....

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

EDIT 2: The below code works fine as well编辑 2:下面的代码也能正常工作

dtf2.plot().get_figure().savefig('output.png')

The gcf method is depricated in V 0.14, The below code works for me: gcf 方法在 V 0.14 中已弃用,以下代码对我有用:

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

You can use ax.figure.savefig() , as suggested in a comment on the question:您可以使用ax.figure.savefig() ,如对问题的评论中所建议:

import pandas as pd

df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in other answers, so you can pick the option you find the most aesthetically pleasing.正如其他答案中所建议的那样,这对ax.get_figure().savefig()没有实际好处,因此您可以选择您认为最美观的选项。 In fact, get_figure() simply returns self.figure :事实上, get_figure()只是返回self.figure

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

So I'm not entirely sure why this works, but it saves an image with my plot:所以我不完全确定为什么会这样,但它用我的情节保存了一个图像:

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

I'm guessing that the last snippet from my original post saved blank because the figure was never getting the axes generated by pandas.我猜我原始帖子中的最后一个片段保存为空白,因为该图从未获得熊猫生成的轴。 With the above code, the figure object is returned from some magic global state by the gcf() call (get current figure), which automagically bakes in axes plotted in the line above.使用上面的代码,图形对象通过 gcf() 调用(获取当前图形)从一些神奇的全局状态返回,它会自动在上图中绘制的轴中烘焙。

It seems easy for me that use plt.savefig() function after plot() function:plot()函数之后使用plt.savefig()函数对我来说似乎很容易:

import matplotlib.pyplot as plt
dtf = pd.DataFrame.from_records(d,columns=h)
dtf.plot()
plt.savefig('~/Documents/output.png')
  • The other answers deal with saving the plot for a single plot, not subplots.其他答案涉及保存单个图的图,而不是子图。
  • In the case where there are subplots, the plot API returns an numpy.ndarray of matplotlib.axes.Axes在有子图的情况下,绘图 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

Plot with pandas.DataFrame.plot()使用pandas.DataFrame.plot()绘图

  • The following example uses kind='hist' , but is the same solution when specifying something other than 'hist'以下示例使用kind='hist' ,但在指定'hist'以外'hist'时是相同的解决方案
  • Use [0] to get one of the axes from the array, and extract the figure with .get_figure() .使用[0]从数组中获取axes之一,并使用.get_figure()提取图形。
fig = df.plot(kind='hist', subplots=True, figsize=(6, 6))[0].get_figure()
plt.tight_layout()
fig.savefig('test.png')

在此处输入图片说明

Plot with pandas.DataFrame.hist()使用pandas.DataFrame.hist()绘图

1: 1:

  • In this example we assign df.hist to Axes created with plt.subplots , and save that fig .在这个例子中,我们分配df.histAxes与创建plt.subplots ,并保存fig
  • 4 and 1 are used for nrows and ncols , respectively, but other configurations can be used, such as 2 and 2 . 41分别用于nrowsncols ,但也可以使用其他配置,例如22
fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(6, 6))
df.hist(ax=ax)
plt.tight_layout()
fig.savefig('test.png')

在此处输入图片说明

2: 2:

  • Use .ravel() to flatten the array of Axes使用.ravel()来展平Axes数组
fig = df.hist().ravel()[0].get_figure()
plt.tight_layout()
fig.savefig('test.png')

在此处输入图片说明

this may be a simpler approach:这可能是一种更简单的方法:

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

ie IE

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM