Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple matplotlib plots in same figure + in to pdf-Python

I'm plotting some data based on pandas dataframes and series. Following is a part of my code. This code gives an error.

RuntimeError: underlying C/C++ object has been deleted


from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
fig = plt.figure()

dfs = df['col2'].resample('10t', how='count')
dfs.plot()
plt.show()

reg = df.groupby('col1').size()
reg.sort()
reg[-10:].plot(kind='barh')
plt.show()

pp = PdfPages('foo.pdf')
fig.savefig(pp, format='pdf') 
pp.close()

I have two questions.

  1. How to plot multiple plots in one output?(Here I get multiple outputs for each and every plot)
  2. How to write all these plots in to one pdf?

I found this as a related question.

like image 335
Nilani Algiriyage Avatar asked Sep 14 '26 05:09

Nilani Algiriyage


2 Answers

Following is the part of code which gave me the expected result, there may be more elegant ways to do this;

def plotGraph(X):
    fig = plt.figure()
    X.plot()
    return fig


plot1 = plotGraph(dfs)
plot2 = plotGraph2(reg[:-10])
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.close()
like image 185
Nilani Algiriyage Avatar answered Sep 16 '26 19:09

Nilani Algiriyage


Please see the following for targeting different subplots with Pandas.

I am assuming you need 2 subplots (in row fashion). Thus, your code may be modified as follows:

from matplotlib import pyplot as plt

fig, axes = plt.subplots(nrows=2)

dfs = df['col2'].resample('10t', how='count')
dfs.plot(ax=axes[0])

reg = df.groupby('col1').size()
reg.sort()
reg[-10:].plot(kind='barh',ax=axes[0])

plt.savefig('foo.pdf')
like image 31
Nipun Batra Avatar answered Sep 16 '26 18:09

Nipun Batra