【发布时间】:2019-11-21 15:26:09
【问题描述】:
我想做的是:
- 以两个子图开始图(堆叠在另一个之上)
- 按键盘上的“x”可:调整图形大小,并在右侧显示第三个图
- 再次按“x”可以:将图形调整回原来的大小,并隐藏第三个绘图(不为第三个绘图留出空间)。
通过下面的示例代码,我得到了这个(matplotlib 3.1.2,MINGW64 中的 Python3,Windows 10):
正如 gif 所示 - 即使在开始状态下,右侧也有一些空白区域(因为我不知道如何解决这个问题,除了定义一个网格之外)。然后,当图形窗口扩展/调整大小时,它不会“完全”调整大小,因此它适合第三个图。
我怎样才能实现第三个图的切换,这样当它被隐藏时,右侧没有额外的空白空间 - 当它显示时,图形完全延伸,因此第三个图适合(包括边距) (编辑:现有/初始两个地块的大小没有变化)?
代码:
#!/usr/bin/env python3
import matplotlib
print("matplotlib.__version__ {}".format(matplotlib.__version__))
import matplotlib.pyplot as plt
import numpy as np
default_size_inch = (9, 6)
showThird = False
def onpress(event):
global fig, ax1, ax2, ax3, showThird
if event.key == 'x':
showThird = not showThird
if showThird:
fig.set_size_inches(default_size_inch[0]+3, default_size_inch[1], forward=True)
plt.subplots_adjust(right=0.85) # leave a bit of space on the right
ax3.set_visible(True)
ax3.set_axis_on()
else:
fig.set_size_inches(default_size_inch[0], default_size_inch[1], forward=True)
plt.subplots_adjust(right=0.9) # default
ax3.set_visible(False)
ax3.set_axis_off()
fig.canvas.draw()
def main():
global fig, ax1, ax2, ax3
xdata = np.arange(0, 101, 1) # 0 to 100, both included
ydata1 = np.sin(0.01*xdata*np.pi/2)
ydata2 = 10*np.sin(0.01*xdata*np.pi/4)
fig = plt.figure(figsize=default_size_inch, dpi=120)
ax1 = plt.subplot2grid((3,3), (0,0), colspan=2, rowspan=2)
ax2 = plt.subplot2grid((3,3), (2,0), colspan=2, sharex=ax1)
ax3 = plt.subplot2grid((3,3), (0,2), rowspan=3)
ax3.set_visible(False)
ax3.set_axis_off()
ax1.plot(xdata, ydata1, color="Red")
ax2.plot(xdata, ydata2, color="Khaki")
fig.canvas.mpl_connect('key_press_event', lambda event: onpress(event))
plt.show()
# ENTRY POINT
if __name__ == '__main__':
main()
【问题讨论】:
-
您需要决定是否要使用一个或两个 gridspec,每个州一个。在第一种情况下,您有方程
margin_left1 + axwidth1 + space + axwidth2 + margin_right1 = figwidth1和margin_left2 + axwidth1 + space + axwidth2 + margin_right2 = figwidth2。在第二种情况下,您有margin_left1 + axwidth1 + margin_right1 = figwidth1和margin_left2 + axwidth1 + space + axwidth2 + margin_right2 = figwidth2。从那些你需要计算要应用的子图参数中。 -
@ImportanceOfBeingErnest - 是否有可能以某种方式“更改”gridspec,而不更改 ax1/ax2 并(重绘)其中的图?编辑:我想我找到了你所说的一个例子(你的):stackoverflow.com/questions/43937066/…
-
是的,可以通过
.update更改网格规范。也可以使用两种不同的网格规范,如该示例所示。
标签: python matplotlib plot