在 mpl_toolkits new_fixed_axis 中更改轴线范围

Change axis line range in mpl_toolkits new_fixed_axis

我正在努力修改我的代码以定义辅助 x 轴的特定范围。下面是创建 2 个 x 轴的相关代码片段及其生成的输出:

from matplotlib import pyplot as plt
import matplotlib.ticker as ticker
from mpl_toolkits.axes_grid.parasite_axes import SubplotHost

...
    x = np.arange(1, len(metric1)+1)  # the label locations
    width = 0.3  # the width of the bars

    fig1 = plt.figure()
    ax1 = SubplotHost(fig1, 111)
    fig1.add_subplot(ax1)
    ax1.axis((0, 14, 0, 20))
    ax1.bar(x, [t[2] for t in metric1], width, label='metric1')
    ax1.bar(x + width, [t[2] for t in metric2], width, label='metric2')
    ax1.bar(x + 2*width, [t[2] for t in metric3], width, label='metric3')

    ax1.set_xticks(x+width)
    ax1.set_xticklabels(['BN', 'B', 'DO', 'N', 'BN', 'B', 'DO', 'N', 'BN', 'B', 'DO', 'N', 'BN', 'B', 'DO', 'N'])
    ax1.axis["bottom"].major_ticks.set_ticksize(0)
    ax2 = ax1.twiny()
    offset = 0, -25 # Position of the second axis
    new_axisline = ax2.get_grid_helper().new_fixed_axis
    ax2.axis["bottom"] = new_axisline(loc="bottom", axes=ax2, offset=offset)
    ax2.axis["top"].set_visible(False)
    ax2.axis["bottom"].minor_ticks.set_ticksize(0)
    ax2.axis["bottom"].major_ticks.set_ticksize(15)

    ax2.set_xticks([0.058, 0.3434, 0.63, 0.915])
    ax2.xaxis.set_major_formatter(ticker.NullFormatter())
    ax2.xaxis.set_minor_locator(ticker.FixedLocator([0.20125, 0.48825, 0.776]))
    ax2.xaxis.set_minor_formatter(ticker.FixedFormatter(['foo', 'bar', 'foo2']))
...

这是当前输出:

我想要的是,不要让辅助 x 轴(foo、bar、foo2)线超出第一个和最后一个 x 刻度线,如下所示(我在 MS paint 中编辑):

感谢任何帮助。

由于没有其他答案,我可以建议一种 non-elegant 方法来满足您的需求。

您可以隐藏轴线并自己“手动”创建一条线:

import matplotlib.lines as lines

ax2.axis["bottom"].line.set_visible(False)

p1 = ax2.axis["bottom"].line.get_extents().get_points()

x1 = 0.058 * (p1[1][0]-p1[0][0]) / (1) + p1[0][0]
x2 = 0.915 * (p1[1][0]-p1[0][0]) / (1) + p1[0][0]

newL = lines.Line2D([x1,x2], [p1[0][1],p1[1][1]], transform=None, axes=ax2,color="k",linewidth=0.5)
ax2.lines.extend([newL,])

在一个简单的例子中,它给出了这样的东西:

相对于:

备选

创建多轴的一种替代方法是使用刺(无寄生轴): https://matplotlib.org/stable/gallery/ticks_and_spines/multiple_yaxis_with_spines.html

在这种情况下,只需更改书脊的边界即可完成您需要的操作。例如,通过将以下行添加到 link

中的代码
par2.spines["right"].set_bounds(10,30)

我们得到这个:

显然,这并不能严格回答您的问题标题,不幸的是,我不知道 new_fixed_axis 的正确方法,因为它可以用于书脊。我希望“手动”创建的行可以解决您的问题,以防其他人提供更好的解决方案。