2

pip install matplotlib

For a simple one pie chart I'm doing this

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')

but I'm having problem when I have to print multiple charts in one pdf. something like this -

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')

after little bit searching over net I found this http://matplotlib.org/1.3.1/faq/howto_faq.html#save-multiple-plots-to-one-pdf-file

from matplotlib.backends.backend_pdf import PdfPages

here are the SOF threads, I have looked at but all of them are using pyplot but I'm using pylab . Plot 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

Can't we do this without using pyplot and only using pylab and pdf_backend? .

What I tried so far is

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()

but its not working, Am I missing something or doing some silly mistake?

basically I want pie charts (multiple) in one pdf.

PS: If you know any better library, which is simple and can do my job please let me know with solution or docs.

Community
  • 1
  • 1
xyz
  • 197
  • 3
  • 16

1 Answers1

3

I think something like this will work better:

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()

the from pylab import * construct is strongly discouraged.

MD. Khairul Basar
  • 4,976
  • 14
  • 41
  • 59
tacaswell
  • 84,579
  • 22
  • 210
  • 199