3

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.

Community
  • 1
  • 1
Nilani Algiriyage
  • 32,876
  • 32
  • 87
  • 121

3 Answers3

5

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()
Nilani Algiriyage
  • 32,876
  • 32
  • 87
  • 121
2

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')
Nipun Batra
  • 11,007
  • 11
  • 52
  • 77
1

matplotlib merges the plots to one figure by default. See the following snippet -

>>> import pylab as plt
>>> randomList = [randint(0, 40) for _ in range(10)]
>>> randomListTwo = [randint(0, 40) for _ in range(10)]
>>> testFigure = plt.figure(1)
>>> plt.plot(randomList)
[<matplotlib.lines.Line2D object at 0x03F24A90>]
>>> plt.plot(randomListTwo)
[<matplotlib.lines.Line2D object at 0x030B9FB0>]
>>> plt.show()

Gives you a figure like the following -

enter image description here

Also, the file can be easily saved in PDF through the commands you posted -

>>> from matplotlib.backends.backend_pdf import PdfPages
>>> pp = PdfPages('foo.pdf')
>>> testFigure.savefig(pp, format='pdf')
>>> pp.close()

This gave me a PDF with a similar figure.

Sukrit Kalra
  • 33,167
  • 7
  • 69
  • 71