0

I'm trying to produce a pdf file (with PdfFile) containing several figures in one page.

The most obvious solution is to use subplots. However, in my case this is not possible because each plot is produced by a different function. For example, there is a function def plotPDF(inputData) that will plot a probability distribution function (PDF), and another function def plotCDF(inputData) that will plot a cumulative distribution function (CDF). My code contains up to 20 different functions that will produce different plots when they are called.

What I want to do is to select some of these plots and produce a pdf file where they are contained in the same page. Following the example of PDF and CDF, I would like to produce a pdf file which contains one page where both plots are next to each other (in a similar way to the subplots).

I have tried to do this with subplots, but I cannot directly call the function within a subplot. That is, the following code wouldn't work:

fig, ax = plt.subplots(nrows=1, ncols=2)

plt.subplot(1, 2, 1)
plotPDF(inputData)

plt.subplot(1, 2, 2)
plotCDF(inputData)

plt.show()

Does anybody know how to solve this issue ? I need to proceed like this because I need the plot functions to be independent for other purposes. Making subplots would mean changing this structure, and it would make the code less versatile.

Thanks in advance !

carlosgguil
  • 33
  • 1
  • 5
  • Use the object oriented API, create a single figure and axes using `fig.add_subplot` or `plt.subplot` and define your functions so they get the axes instance as argument. – MaxNoe Jan 03 '20 at 22:49

2 Answers2

0

I don't know if there's a way to do what you are asking, maybe someone else will know...

but

the recommended way to write a plotting function is to pass a reference to an Axes object to the function, and write the function to use that axes to do the plotting.

so in your case:

def plotPDF(data, ax=None):
    ax = ax or plt.gca() # if no axes, use current axes
    plt.sca(ax) # set axes as current axes (important if you are using the pyplot API)
    # the rest of the function goes here

def plotCDF(data, ax=None):
    ax = ax or plt.gca()
    plt.sca(ax)
    (...)


fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2)
plotPDF(inputData, ax=ax1)
plotCDF(inputData, ax=ax2)
plt.show()
Diziet Asahi
  • 38,379
  • 7
  • 60
  • 75
0

Have you read this answer to a similar post? The answers in that post contain many ways to save an image into a pdf file, and only one (the matplotlib backend) requires subplots, as far as I know.

You can also save the files separately as png files, then use LaTeX / Word / another primitive way to arrange them into a pdf, which could be tedious.

Otherwise, could you maybe elaborate why using subplots wouldn't work with your functions? Maybe there is a way to use subplots, but then you'll need to show us the code.

mehfluffy
  • 49
  • 1
  • 9