可能的副本:How to assign a plot to a variable and use the variable as the return value in a Python function 但是答案对我没有用。
考虑如下示例中生成的图形: https://networkx.github.io/documentation/networkx-1.9/examples/drawing/four_grids.html
我有一个列表figs
代表图表,我想在一个布局中组成这些图表。
已编辑以发表评论
请注意, nx.draw()
会生成一个matplotlib.figure.Figure
对象。
nx.draw()
不返回matplotlib.figure.Figure
对象,但是我可以将生成的图形存储在变量中,如下所示:
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
所以我可以生成如下列表:
figs = [ graph_to_figure(g),graph_to_figure(g)]
我现在想对结果进行分页以创建PDF。
我尝试过类似的事情:
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
但是它会出错,因为图片无花果无法以float格式转换:它需要真实的图片。
因此,我尝试查看了文档,但是无法弄清楚如何简单地将matplotlib.figure.Figure对象放置在网格上。
第二次尝试
查看: Adding figures to subplots in Matplotlib
它显示了使用子图的示例:
fig,ax = plt.subplots(2,1,sharex=True)
plot_fig_1(...,ax[0])
plot_fig_2(...,ax[1])
但是我却是一个matplotlib.figure对象,而不是matplotlib.pyplot对象。
我可能会这样:
pagefig.add_subplot( plot_num)
nx.draw(G,font_size=8)
plot_num += 1
但是我想将图形添加为变量。
pagefig.add_subplot( plot_num)
figs[0] # doesn't work
plot_num += 1
如何使用引用matplotlib.figure.Figure
对象的变量来组成布局?
如何将变量添加到网格?
请注意,我使用的不是图,也不是图像,而是数字。