【问题标题】:How to assign a variable to a matplotlib figure object and reuse it in layout如何将变量分配给 matplotlib 图形对象并在布局中重用它
【发布时间】: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


【解决方案1】:

您需要先创建一个图形。您也可以直接创建 4 个轴并绘制到这些轴。这应该如下所示(未经测试):

fig, ax_arr = plt.subplots(2,2)

for ax, g, pos in zip(ax_arr.flat, list_of_g, list_of_pos):
    nx.draw(g, pos, font_size=8, ax=ax)

plt.show()

【讨论】:

  • 感谢您的想法,奥斯卡·王尔德:D。似乎唯一的方法是在循环中生成图纸。不过,我希望使用一个变量。如果我用问题中描述的方法存储的图形替换nx.draw(g, pos, font_size=8, ax=ax),它将不起作用:for ax, fig in zip(ax_arr.flat, figs[:3]): fig # plt.show() where figs = [ graph_to_figure(g), ... ,graph_to_figure(g) 我还尝试覆盖当前绘图的轴,例如fig.axes[0] = ax,但是我看到空图。我不知道绘图是实际渲染的,还是渲染但不在子图上。
  • 是的。正如已经评论的那样,您不能将图形添加到另一个图形。另一种选择是将每个图形保存为 pdf,然后使用一些 pdf writer 程序将 4 个 pdf 组合成一个 pdf。
  • 我明白了。不过,这将是一个不错的功能!顺便说一句,我阅读了您的个人资料,并且对 matplotlib 非常了解。请问您,我是在与其中一位主要贡献者交谈吗?
  • 由于 matplotlib 使用的转换系统,该功能很难实现。但重写转换系统本质上意味着重写 matplotlib 本身。我是开发团队的一员,做了很多贡献,但我的角色并不是项目的“关键”。
  • 您也可以编写嵌套的子图规范,但事后不能。 matplotlib.org/3.1.1/tutorials/intermediate/…
猜你喜欢
  • 2019-04-15
  • 2021-06-08
  • 1970-01-01
  • 2020-11-15
  • 1970-01-01
  • 2021-01-01
  • 2014-08-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多