【发布时间】:2020-03-07 15:07:59
【问题描述】:
可能重复: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
但它会报错,因为图像 fig 不能在 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,pos,font_size=8)
plot_num += 1
但我想将图形添加为变量。
pagefig.add_subplot( plot_num)
figs[0] # doesn't work
plot_num += 1
如何利用引用matplotlib.figure.Figure对象的变量来组合布局?
如何将变量添加到网格中?
请注意,我使用的不是图表,也不是图像,而是数字。
【问题讨论】:
-
本质上,您是在尝试将一个(或多个)图形插入一个新图形。这对于 matplotlib 是不可能的。图形本身就是一个实体,不能用来组成其他图形。但是,
nx.draw()返回这样的数字的前提似乎也是错误的。它应该返回None。你能验证并更正这个问题吗?
标签: python variables matplotlib layout figure