如何使用Matplotlib使用交互式缩放工具重新调整轴的限制(添加到主体绘图)?

2024-09-30 02:27:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下脚本显示两个y轴和一个公共x轴的信息。你知道吗

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA

#creating a host plot with x and y axis
hostplot = host_subplot(111, axes_class=AA.Axes)

#creating a second y axis
extra_y_axis = hostplot.twinx()
extra_y_axis.set_navigate_mode(True)
extra_y_axis.set_navigate(True)
print extra_y_axis.can_zoom() #prints true on output

hostplot.set_xlabel("host_x")
hostplot.set_ylabel("host_y")
extra_y_axis.set_ylabel("extra_y")

hostplot.plot([0, 1, 2], [0, 1, 2])
extra_y_axis.plot([0, 1, 2], [0, 3, 2])

plt.draw()
plt.show()

之后,我使用了左下角托盘中的“缩放到矩形”工具,如下所示:

as shown。你知道吗

我得到了以下结果:

following output。你知道吗

请注意两张图片中的y轴比例。虽然主机绘图的缩放功能正常工作,但我无法使额外的y轴重新缩放,它始终保持恒定的缩放比例(因此我无法使用第二个轴放大绘图)。你知道吗

如何使所有轴在小范围缩放时重新缩放?你知道吗

谢谢


Tags: importcreatinghostplotaspltextrampl
1条回答
网友
1楼 · 发布于 2024-09-30 02:27:12

我把你的问题追溯到axes\u grid1工具箱的问题。如果您不需要使用此工具箱,您可以通过按常规方式初始化图形来轻松解决问题:

import matplotlib.pyplot as plt
#creating a host plot with x and y axis
fig, hostplot = plt.subplots()

#creating a second y axis
extra_y_axis = hostplot.twinx()

hostplot.set_xlabel("host_x")
hostplot.set_ylabel("host_y")
extra_y_axis.set_ylabel("extra_y")

hostplot.plot([0, 1, 2], [0, 1, 2])
extra_y_axis.plot([0, 1, 2], [0, 3, 2])

plt.show()

如果确实要使用工具箱,则必须添加几条线以使两个y轴一起缩放和变换:

import matplotlib.transforms as mtransforms
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.parasite_axes import SubplotHost

fig = plt.figure()
ax1 = SubplotHost(fig, 1, 1, 1)

#set the scale difference between the two y axes
aux_trans = mtransforms.Affine2D().scale(sx = 1.,sy= 1.5)
ax2 = ax1.twin(aux_trans)

fig.add_subplot(ax1)

ax1.plot([0, 1, 2], [0, 1, 2])
ax2.plot([0, 1, 2], [0, 3, 2])
ax1.set_ylim(0,3)

plt.show()

相关问题 更多 >

    热门问题