Multiple matplotlib plots in same figure + in to pdf-Python
Solution 1
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()
Solution 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')
Solution 3
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 -
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.
Nilani Algiriyage
A PhD researcher at Massey, Wellington, New Zealand. Research Interests : Deep Learning, AI
Updated on June 06, 2022Comments
-
Nilani Algiriyage almost 2 years
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.
- How to plot multiple plots in one output?(Here I get multiple outputs for each and every plot)
- How to write all these plots in to one pdf?
I found this as a related question.