在 matplotlib 中使用箭头获取 x 和 y 轴并控制 x 和 y 标签的位置

gxy*_*xyd 1 python plot matplotlib

嗨这里给出的情节https://matplotlib.org/examples/axes_grid/demo_axisline_style.html

在 y 轴右侧的 y 轴上有标签,但我希望它们位于 y 轴的左侧。我该怎么做?

from mpl_toolkits.axes_grid.axislines import SubplotZero
from matplotlib.transforms import BlendedGenericTransform
import matplotlib.pyplot as plt
import numpy

if 1:
    fig = plt.figure(1)
    ax = SubplotZero(fig, 111)
    fig.add_subplot(ax)

    ax.axhline(linewidth=1.7, color="black")
    ax.axvline(linewidth=1.7, color="black")

    plt.xticks(range(11))

    ax.text(0, 1.05, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
    ax.text(1.05, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

    for direction in ["xzero", "yzero"]:
        ax.axis[direction].set_axisline_style("-|>")
        ax.axis[direction].set_visible(True)

    ax.axis["yzero"].set_visible(False)

    for direction in ["right", "top"]:
        ax.axis[direction].set_visible(False)

    plt.yticks(range(11))
    plt.grid(True)

    plt.show()
Run Code Online (Sandbox Code Playgroud)

这个代码块给了我这个。但是 y 轴的箭头丢失了。

小智 5

在您的代码中添加了 2 行。希望能帮助到你。

  1. 添加以将标签从右向左反转。

    ax.axis["yzero"].invert_ticklabel_direction()
    
    Run Code Online (Sandbox Code Playgroud)
  2. 将“左”设置为不可见

    for direction in ["left", "right", "top"]: 
    
    Run Code Online (Sandbox Code Playgroud)

在您的代码中更新:

    from mpl_toolkits.axisartist.axislines import SubplotZero
    from matplotlib.transforms import BlendedGenericTransform
    import matplotlib.pyplot as plt
    import numpy

    if 1:
        fig = plt.figure(1)
        ax = SubplotZero(fig, 111)
        fig.add_subplot(ax)

        ax.axhline(linewidth=1.7, color="black")
        ax.axvline(linewidth=1.7, color="black")

        plt.xticks(range(11))

        ax.text(0, 1.05, 'y', transform=BlendedGenericTransform(ax.transData, ax.transAxes), ha='center')
        ax.text(1.05, 0, 'x', transform=BlendedGenericTransform(ax.transAxes, ax.transData), va='center')

        for direction in ["xzero", "yzero"]:
            ax.axis[direction].set_axisline_style("-|>")
            ax.axis[direction].set_visible(True)

        # added to invert the label from right to left.
        ax.axis["yzero"].invert_ticklabel_direction()

        # set 'left' to be invisible
        for direction in ["left", "right", "top"]:  # for direction in ["right", "top"]:
            ax.axis[direction].set_visible(False)

        plt.yticks(range(11))
        plt.grid(True)

        plt.show()
Run Code Online (Sandbox Code Playgroud)