matplotlib:隐藏子图并用其他子图填充空间 [英] matplotlib: hide subplot and fill space with other subplots

查看:408
本文介绍了matplotlib:隐藏子图并用其他子图填充空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含三个垂直排列的子图的图.单击该图后,我希望第二个子图ax2隐藏,而其他图填充该空间.再次单击该图,将恢复原始图和布局.

I've got a figure that contains three subplots which are arranged vertically. Once I click into the figure, I want the second subplot ax2 to be hidden and the other plots to fill the space. A second click into the figure should restore the original plot and layout.

隐藏子图ax2没问题,但是如何重新排列其他子图的位置?

Hiding the subplot ax2 isn't a problem, but how can I rearrange the positions of the other subplots?

我尝试使用set_positionset_subplotspec方法创建一个新的GridSpec,但是没有任何结果.我确定我在这里缺少任何东西,任何帮助将不胜感激.

I've tried creating a new GridSpec, using the set_position and set_subplotspec methods, but nothing worked out. I'm sure I'm missing something here, any help would be appreciated.

这是我的代码:

import matplotlib.pyplot as plt
from matplotlib import gridspec

fig = plt.figure()

gs = gridspec.GridSpec(3, 1, height_ratios=[5, 2, 1])
ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharex=ax1)
ax3 = fig.add_subplot(gs[2], sharex=ax2)

visible = True

def toggle_ax2(event):
    global visible
    visible = not visible
    ax2.set_visible(visible)
    plt.draw()

fig.canvas.mpl_connect('button_press_event', toggle_ax2)
plt.show()

推荐答案

您可以定义两个不同的GridSpec.一个将具有3个子图,另一个将2个.根据中间轴的可见性,您可以更改其他两个轴的位置,使其服从第一个或第二个GridSpec.
(不需要任何虚拟人物,就像其他答案可能会建议的那样.)

You can define two different GridSpecs. One would have 3 subplots, the other 2. Depending on the visibility of the middle axes, you change the position of the other two axes to obey to the first or second GridSpec.
(There is no need for any dummy figure or so, like other answers might suggest.)

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure()

gs = gridspec.GridSpec(3, 1, height_ratios=[5, 2, 1], hspace=0.3)
gs2 = gridspec.GridSpec(2,1, height_ratios=[5,3])

ax1 = fig.add_subplot(gs[0])
ax2 = fig.add_subplot(gs[1], sharex=ax1)
ax3 = fig.add_subplot(gs[2], sharex=ax2)

ax1.plot([1,2,3], [1,2,3], color="crimson")
ax2.plot([1,2,3], [2,3,1], color="darkorange")
ax3.plot([1,2,3], [3,2,1], color="limegreen")

visible = True

def toggle_ax2(event):
    global visible
    visible = not visible
    ax2.set_visible(visible)
    if visible:
        ax1.set_position(gs[0].get_position(fig))
        ax3.set_position(gs[2].get_position(fig))
    else:
        ax1.set_position(gs2[0].get_position(fig))
        ax3.set_position(gs2[1].get_position(fig))

    plt.draw()

fig.canvas.mpl_connect('button_press_event', toggle_ax2)
plt.show()

左:原始;右:单击

这篇关于matplotlib:隐藏子图并用其他子图填充空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆