【问题标题】:Pylab/Matplotlib multilple pie charts into one PDFPylab/Matplotlib 将多个饼图合并为一个 PDF
【发布时间】:2014-11-11 20:39:39
【问题描述】:

点安装 matplotlib

对于一个简单的饼图,我正在这样做

from pylab import *

figure(3, figsize=(4,4))
axes([0.1, 0.1, 0.8, 0.8])
labels=['Red', 'Blue', 'Green', 'Brown']
fracs=[40, 30, 20, 10]
pie(fracs,labels=labels)

savefig('chart.png') # or savefig('chart.pdf')

但是当我必须在一个 pdf 中打印多个图表时,我遇到了问题。 像这样 -

for x in mylist:
    figure(3, figsize=(4,4))
    axes([0.1, 0.1, 0.8, 0.8])
    labels=x['labels']   # ['Red', 'Blue', 'Green', 'Brown']
    fracs=x['fracs']    # [40, 30, 20, 10]
    pie(fracs,labels=labels)
    savefig('chart.png')

在网上搜索了一下后,我发现了这个http://matplotlib.org/1.3.1/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file

from matplotlib.backends.backend_pdf import PdfPages

这里是 SOF 线程,我看过,但他们都在使用 pyplot 但我正在使用 pylabPlot and save multiple figures of group by function as pdf

Matplotlib.pyplot : Save the plots into a pdf

Saving plots to pdf files using matplotlib

我们不能不使用 pyplot 而只使用 pylab 和 pdf_backend 来做到这一点吗? .

到目前为止我尝试的是

from pylab import *
from matplotlib.backends.backend_pdf import PdfPages

pp = PdfPages('long.pdf')

for x in mylist:
        figure(3, figsize=(4,4))
        axes([0.1, 0.1, 0.8, 0.8])
        labels=x['labels']   # ['Red', 'Blue', 'Green', 'Brown']
        fracs=x['fracs']    # [40, 30, 20, 10]
        p = pie(fracs,labels=labels)  # slightly difference in these two lines (assigning values this time)
        p.savefig(pp, format='pdf')   #
pp.savefig()

但它不起作用,我是错过了什么还是犯了一些愚蠢的错误?

基本上我想要一个 pdf 中的饼图(多个)。

PS:如果您知道任何更好的库,它很简单并且可以完成我的工作,请通过解决方案或文档告诉我。

【问题讨论】:

    标签: python python-2.7 python-3.x numpy matplotlib


    【解决方案1】:

    我认为这样会更好:

    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_pdf import PdfPages
    
    pp = PdfPages('long.pdf')
    fig = plt.figure(3, figsize=(4,4))
    ax = plt.axes([0.1, 0.1, 0.8, 0.8])
    for x in mylist:
        ax.cla()    
        labels=x['labels']   # ['Red', 'Blue', 'Green', 'Brown']
        fracs=x['fracs']    # [40, 30, 20, 10]
        p = pie(fracs,labels=labels)  
        # slightly difference in these two lines (assigning values this time)
        fig.savefig(pp, format='pdf')   #
    pp.close()
    

    强烈建议不要使用from pylab import * 构造。

    【讨论】:

      猜你喜欢
      • 2013-03-03
      • 2014-10-16
      • 2015-07-20
      • 2022-01-22
      • 2013-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多