【问题标题】:Matplotlib - User changes amount of subplotsMatplotlib - 用户更改子图的数量
【发布时间】:2019-03-14 09:39:09
【问题描述】:

在我的代码中,用户应该能够更改图中子图的数量。所以首先有两个子图:

我使用以下代码:

ax1 = figure.add_sublots(2,1,1)
ax2 = figure.add_sublots(2,1,2)

如果按下加号按钮,则应添加一个子图:

我应该怎么做?有没有类似的命令

ax1.change_subplot(3,1,1)
ax2.change_subplot(3,1,2)
ax3 = figure.add_sublots(3,1,3)

还是我必须删除所有子图并重新绘制它们(我想避免)?

【问题讨论】:

  • 本文档可能对matplotlib.org/api/_as_gen/…有帮助
  • 我知道这个文档。它没有写在那里,或者我不明白。可以添加地块,但不能改变现有地块的位置。

标签: python matplotlib position axis figure


【解决方案1】:

这是一种选择。您可以为要显示的每个子图数量创建一个新的 GridSpec,并根据该 gridspec 设置轴的位置。

import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.widgets import Button

class VariableGrid():
    def __init__(self,fig):
        self.fig = fig
        self.axes = []
        self.gs = None
        self.n = 0

    def update(self):
        if self.n > 0:
            for i,ax in zip(range(self.n), self.axes):
                ax.set_position(self.gs[i-1].get_position(self.fig))
                ax.set_visible(True)

            for j in range(len(self.axes),self.n,-1 ):
                print(self.n, j)
                self.axes[j-1].set_visible(False)
        else:
            for ax in self.axes:
                ax.set_visible(False)
        self.fig.canvas.draw_idle()


    def add(self, evt=None):
        self.n += 1
        self.gs= GridSpec(self.n,1)
        if self.n > len(self.axes):
            ax = fig.add_subplot(self.gs[self.n-1])
            self.axes.append(ax)
        self.update()

    def sub(self, evt=None):
        self.n = max(self.n-1,0)
        if self.n > 0:
            self.gs= GridSpec(self.n,1)
        self.update()


fig = plt.figure()

btn_ax1 = fig.add_axes([.8,.02,.05,.05])
btn_ax2 = fig.add_axes([.855,.02,.05,.05])
button_add =Button(btn_ax1, "+")
button_sub =Button(btn_ax2, "-")


grid = VariableGrid(fig)
button_add.on_clicked(grid.add)
button_sub.on_clicked(grid.sub)

plt.show()

【讨论】:

    【解决方案2】:

    我正在寻找的命令是:

    ax1.change_geometry(3,1,1)
    

    使用此命令可以重新排列子批次。 我在这里找到了这个解决方案: Dynamically add subplots in matplotlib with more than one column

    【讨论】:

      猜你喜欢
      • 2017-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-27
      • 1970-01-01
      • 1970-01-01
      • 2012-11-02
      相关资源
      最近更新 更多