如何将基于 Pandas 数据框的图形导出为 pdf?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35484458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to export to pdf a graph based on a pandas dataframe?
提问by ??????
I have a pandas dataframe and I am using the useful .plot() method.
我有一个Pandas数据框,我正在使用有用的 .plot() 方法。
The dataframe looks like
数据框看起来像
col1 col2 col3
1 2 3
7 0 3
1 2 2
I therefore use df.plot()
to get the chart I want.
因此df.plot()
,我用来获取我想要的图表。
Problem is, I would like to export the chart to a pdf. Ideally, I could also generate other charts (based on this dataframe) and add them to the pdf.
问题是,我想将图表导出为 pdf。理想情况下,我还可以生成其他图表(基于此数据框)并将它们添加到 pdf 中。
It is possible to do so ? Thanks!
有可能这样做吗?谢谢!
回答by tmdavison
To output a single figure as a pdf, you can use plt.savefig('myfile.pdf')
:
要将单个图形输出为 pdf,您可以使用plt.savefig('myfile.pdf')
:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([[1,2,3],[7,0,3],[1,2,2]],columns=['col1','col2','col3'])
df.plot()
plt.savefig('myfile.pdf')
To output multiple images to one pdf, you can use PdfPages
, as shown in the example here.
可以输出多种图像一个PDF格式,你可以使用PdfPages
,如图所示的例子在这里。
A minimal example:
一个最小的例子:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.backends.backend_pdf import PdfPages
df = pd.DataFrame([[1,2,3],[7,0,3],[1,2,2]],columns=['col1','col2','col3'])
with PdfPages('multipage_pdf.pdf') as pdf:
df.plot()
pdf.savefig()
plt.close()
df.plot(kind='bar')
pdf.savefig()
plt.close()
回答by fernandezcuesta
The following should do:
以下应该做:
plot = df.plot()
plot.get_figure().savefig('output.pdf', format='pdf')
It actually depends in whether or not your backend supports pdf output (most do). Check with:
这实际上取决于您的后端是否支持 pdf 输出(大多数支持)。检查:
'pdf' in plot.get_figure().canvas.get_supported_filetypes()
回答by Julien Spronck
The following code creates a pdf with 2 pages (one plot on each page):
以下代码创建一个 2 页的 pdf(每页一个图):
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
df = pd.DataFrame({'col1': [1, 3, 7], 'col2': [1, 4, 5], 'col3': [2, 7, 1]})
with PdfPages('foo.pdf') as pdf:
fig=df.plot(x='col1', y='col2').get_figure()
pdf.savefig(fig)
fig=df.plot(x='col1', y='col3').get_figure()
pdf.savefig(fig)
You can add as many plots as you want by repeating the last two lines.
您可以通过重复最后两行来添加任意数量的图。