0

I am trying to combine my 4 pages of 4 different graphs into 1 page of graphs organized in a 2x2 fashion. I am using 'Pdfpages' in Python.

In Matplotlib I see that we can do the following to create multiple plots:

# Initialise the subplot function using number of rows and columns
figure, axis = plt.subplots(2, 2)
  
# For Sine Function
axis[0, 0].plot(X, Y1)
axis[0, 0].set_title("Sine Function")
  
# For Cosine Function
axis[0, 1].plot(X, Y2)
axis[0, 1].set_title("Cosine Function")
... etc
# Then use pdfpages, e.g. pdf.savefig(figure)

However, I have the following using pandas dataframes directly:

df1.plot(x='col1', y=['col2', 'col3'], style='-', title=title1)
pdf.savefig()
plt.close()

df2.plot(x='col1', y=['col2', 'col3'], style='-', title=title2)
pdf.savefig()
plt.close()

df3.plot(x='col1', y=['col2', 'col3'], style='-', title=title3)
pdf.savefig()
plt.close()

df4.plot(x='col1', y=['col2', 'col3'], style='-', title=title4)
pdf.savefig()
plt.close()

How can I take df1...df4 and make them into a 2x2 plot and then save this onto a single page?

halfer
  • 19,824
  • 17
  • 99
  • 186
JDS
  • 16,388
  • 47
  • 161
  • 224

1 Answers1

0

I believe you can use:

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

And use savefig() and close() after you use .plot() for the four dataframes. Hope this works! source

Hanna
  • 81
  • 7
  • This creates the subplots (as OP already alluded to), but it does not actually plot into each subplot. You need to use the `ax` parameter of `DataFrame.plot`. – BigBen Oct 24 '22 at 19:27