尝试将Pandas DataFrame中的matplotlib绘图写入pdf时出错

时间:2021-10-07 23:48:10

I'm trying to write a plot from matplotlib to a pdf file but getting an error.

我正在尝试从matplotlib写一个绘图到pdf文件但是收到错误。

I'm creating a plot using matplotlib from a Pandas DataFrame like this:

我正在使用来自Pandas DataFrame的matplotlib创建一个情节,如下所示:

bplot = dfbuild.plot(x='Build',kind='barh',stacked='True')

From the documentation: http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file

来自文档:http://matplotlib.org/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file

It seems like I should be doing it this way:

好像我应该这样做:

from matplotlib.backends.backend_pdf import PdfPages
pp = PdfPages(r'c:\temp\page.pdf')
figure = bplot.fig
pp.savefig(figure)
pp.close()

I get this error:

我收到此错误:

AttributeError: 'AxesSubplot' object has no attribute 'fig'

2 个解决方案

#1


1  

The problem is that dfbuild.plot returns an AxesSubplot and not a Figure instance, which is required by the savefig function.

问题是dfbuild.plot返回一个AxesSubplot而不是一个图实例,这是savefig函数所需要的。

This solves the issue:

这解决了这个问题:

pp.savefig(bplot.figure)

#2


0  

I works when I do it this way.

我这样做的时候会工作。

pp = PdfPages(r'c:\temp\page.pdf')
dfbuild.plot(x=['Build','Opperator'],kind='barh',stacked='True')
pp.savefig()
pp.close()

From Saving plots to pdf files using matplotlib

从使用matplotlib将图表保存到pdf文件

#1


1  

The problem is that dfbuild.plot returns an AxesSubplot and not a Figure instance, which is required by the savefig function.

问题是dfbuild.plot返回一个AxesSubplot而不是一个图实例,这是savefig函数所需要的。

This solves the issue:

这解决了这个问题:

pp.savefig(bplot.figure)

#2


0  

I works when I do it this way.

我这样做的时候会工作。

pp = PdfPages(r'c:\temp\page.pdf')
dfbuild.plot(x=['Build','Opperator'],kind='barh',stacked='True')
pp.savefig()
pp.close()

From Saving plots to pdf files using matplotlib

从使用matplotlib将图表保存到pdf文件