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

时间:2019-06-06 10:02:54

标签: python matplotlib plot

嗨,这里的情节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()

这个代码块给了我。但是缺少y轴上的箭头。

1 个答案:

答案 0 :(得分:3)

在代码中添加了2行。希望对您有所帮助。

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

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

    for direction in ["left", "right", "top"]: 
    

已更新您的代码:

    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()