阻止轴展开matplotlib

时间:2018-07-20 08:56:57

标签: python-3.x matplotlib

我一直在使用下面的网站代码来创建和使用子图行的检查按钮:

https://matplotlib.org/gallery/widgets/check_buttons.html

但是当我拉动图形窗口的边缘时,我似乎无法阻止复选按钮的轴(rax)扩展,我只希望带有线的图扩展。我已经尝试过了,但是似乎无法完成工作:

t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)

fig, ax = plt.subplots()
l0, = ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz')
l1, = ax.plot(t, s1, lw=2, color='r', label='4 Hz')
l2, = ax.plot(t, s2, lw=2, color='g', label='6 Hz')
plt.subplots_adjust(left=0.2)

lines = [l0, l1, l2]

rax = plt.axes([0.05, 0.4, 0.1, 0.15])
rax.autoscale(enable=FALSE, tight=TRUE)    #this is the part i don't want expanding
labels = [str(line.get_label()) for line in lines]
visibility = [line.get_visible() for line in lines]
check = CheckButtons(rax, labels, visibility)


def func(label):
    index = labels.index(label)
    lines[index].set_visible(not lines[index].get_visible())
    plt.draw()

check.on_clicked(func)
plt.show()

有没有办法做到这一点?

谢谢!

1 个答案:

答案 0 :(得分:1)

问题可以转化为如何以绝对(像素)坐标的宽度和高度固定图形坐标中的轴的位置。这可以通过将轴定位器设置为a mpl_toolkits.axes_grid1.inset_locator.AnchoredSizeLocator通过ax.set_axes_locator

import matplotlib.pyplot as plt
import matplotlib.transforms as mtrans
from mpl_toolkits.axes_grid1.inset_locator import AnchoredSizeLocator

fig, ax = plt.subplots()

# Create axes, which is positionned in figure coordinates,
# with width and height fixed in inches.

# axes extent in figure coordinates (width & height ignored)
axes_extent = [0.03, 0.5, 0, 0]
# add axes to figure
rax = fig.add_axes(axes_extent)
# create locator: Position at (0.03, 0.5) in figure coordinates,
# 0.7 inches wide and tall, pinned at left center of bbox.
axes_locator = AnchoredSizeLocator(mtrans.Bbox.from_bounds(*axes_extent),
                                   .7, .7, loc="center left",
                                   bbox_transform=fig.transFigure,
                                   borderpad=0)
rax.set_axes_locator(axes_locator)

现在,当图形尺寸更改时,轴将停留在相同的相对位置,而不会更改其宽度和高度。