Possible duplicate of : How to assign a plot to a variable and use the variable as the return value in a Python function but answer did not worked for me.
Consider a figure generated like in this examples: https://networkx.github.io/documentation/networkx-1.9/examples/drawing/four_grids.html
I have a list of figures figs
representing graphs, which I want to compose in a layout.
EDITED to address the comment
Note that nx.draw()
generates a matplotlib.figure.Figure
object.
nx.draw()
does not return a matplotlib.figure.Figure
object, however I can store the generated figure in a variable, like this:
def graph_to_figure(g):
fig = plt.figure()
nx.draw(g,pos,font_size=8)
plt.close()
return fig
type(graph_to_figure(g))
>> matplotlib.figure.Figure
so I can generate a list of figures as:
figs = [ graph_to_figure(g), graph_to_figure(g)]
I now want to paginate results to create a pdf.
I tried something like:
plot_num = 221 #2 rows, 2 columns, start from index 1
pagefig = plt.figure(figsize=(10, 10))
for fig in figs:
pagefig.add_subplot( plot_num)
plt.imshow(fig) # return error! any api like plt.add_figure( ) to add the figure to the plot?
plot_num += 1
But it will give error, for the image fig cannot be converted in float : it is expecting a real image.
So I tried and looked at the documentation, but caould not figure out how to simply place a matplotlib.figure.Figure object on the grid.
Second attempt
Looking at: Adding figures to subplots in Matplotlib
it shows example making use of subplot:
fig, ax = plt.subplots(2, 1, sharex=True)
plot_fig_1(..., ax[0])
plot_fig_2(..., ax[1])
but instead I a matplotlib.figure object, not a matplotlib.pyplot object..
I may do something like this:
pagefig.add_subplot( plot_num)
nx.draw(G,pos,font_size=8)
plot_num += 1
but I want to add the figure as a variable.
pagefig.add_subplot( plot_num)
figs[0] # doesn't work
plot_num += 1
How to compose layouts making use of variables referencing to matplotlib.figure.Figure
objects?
How to add the variables to a grid ?
Please note I am not using plots, nor images, but figures.