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

t1qtbnec  于 2023-10-24  发布在  Python
关注(0)|答案(6)|浏览(187)

我使用pandas从一个框架生成一个图,我想保存到一个文件中:

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

看起来最后一行,使用matplotlib的savefig,应该可以做到这一点。但是这段代码产生了以下错误:

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

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

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

我想我需要以某种方式将plot()返回的子图添加到一个图中,以便使用savefig。我还想知道这是否与AxesSubPlot类后面的magic有关。
编辑:
下面的工程(提高没有错误),但留给我一个空白页的形象..

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

编辑2:下面的代码也可以正常工作

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

u7up0aaq1#

gcf方法在V0.14中被删除,下面的代码对我来说很有效:

  1. plot = dtf.plot()
  2. fig = plot.get_figure()
  3. fig.savefig("output.png")
h22fl7wq

h22fl7wq2#

你可以使用ax.figure.savefig(),就像对这个问题的评论中建议的那样:

  1. import pandas as pd
  2. df = pd.DataFrame([0, 1])
  3. ax = df.plot.line()
  4. ax.figure.savefig('demo-file.pdf')

与其他答案中建议的ax.get_figure().savefig()相比,这没有实际好处,因此您可以选择您认为最美观的选项。实际上,get_figure()只是返回self.figure

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

kulphzqa3#

所以我不完全确定为什么这是有效的,但它保存了一个图像与我的情节:

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

我猜我最初的帖子中的最后一个片段保存为空白,因为图从来没有得到pandas生成的轴。使用上面的代码,gcf()调用(get current figure)从一些神奇的全局状态返回图对象,它自动烘焙上面一行中绘制的轴。

aiqt4smr

aiqt4smr4#

对我来说,在plot()函数之后使用plt.savefig()函数似乎很容易:

  1. import matplotlib.pyplot as plt
  2. dtf = pd.DataFrame.from_records(d,columns=h)
  3. dtf.plot()
  4. plt.savefig('~/Documents/output.png')
qni6mghb

qni6mghb5#

  • 其他的答案是将情节保存为单个情节,而不是子情节。
  • 在存在子图的情况下,绘图API返回matplotlib.axes.Axesnumpy.ndarray
  1. import pandas as pd
  2. import seaborn as sns # for sample data
  3. import matplotlib.pyplot as plt
  4. # load data
  5. df = sns.load_dataset('iris')
  6. # display(df.head())
  7. sepal_length sepal_width petal_length petal_width species
  8. 0 5.1 3.5 1.4 0.2 setosa
  9. 1 4.9 3.0 1.4 0.2 setosa
  10. 2 4.7 3.2 1.3 0.2 setosa
  11. 3 4.6 3.1 1.5 0.2 setosa
  12. 4 5.0 3.6 1.4 0.2 setosa

使用pandas.DataFrame.plot()绘图

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

使用pandas.DataFrame.hist()绘图

1:

  • 在本例中,我们将df.hist分配给用plt.subplots创建的Axes,并保存fig
  • 41分别用于nrowsncols,但是也可以使用其他配置,例如22
  1. fig, ax = plt.subplots(nrows=4, ncols=1, figsize=(6, 6))
  2. df.hist(ax=ax)
  3. plt.tight_layout()
  4. fig.savefig('test.png')

2:

  • 使用.ravel()来展平Axes的数组
  1. fig = df.hist().ravel()[0].get_figure()
  2. plt.tight_layout()
  3. fig.savefig('test.png')

展开查看全部
ki0zmccv

ki0zmccv6#

这可能是一个更简单的方法:
(DesiredFigure).get_figure().savefig('figure_name.png')

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

相关问题