【问题标题】:Python Matplotlib Y-Axis ticks on Right Side of Plot绘图右侧的 Python Matplotlib Y 轴刻度
【发布时间】:2012-05-08 10:10:33
【问题描述】:

我有一个简单的线图,需要将 y 轴刻度从图的(默认)左侧移动到右侧。关于如何做到这一点的任何想法?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    使用ax.yaxis.tick_right()

    例如:

    from matplotlib import pyplot as plt
    
    f = plt.figure()
    ax = f.add_subplot(111)
    ax.yaxis.tick_right()
    plt.plot([2,3,4,5])
    plt.show()
    

    【讨论】:

    • 很好的答案,你会得到 +1,我会给你另一个 +1 的图片,但我仅限于 1。
    • 有趣的是,这会导致刻度名称返回,即使它们应该被 sharey=True 抑制
    • 如果我想要左右两边的刻度和标签怎么办?
    • 我没有弄清楚原因,但是如果您有带有sharey=True 的子图,这就会中断。
    • 让刻度出现在左侧右侧的命令是什么?谢谢!
    【解决方案2】:

    对于正确的标签,使用ax.yaxis.set_label_position("right"),即:

    f = plt.figure()
    ax = f.add_subplot(111)
    ax.yaxis.tick_right()
    ax.yaxis.set_label_position("right")
    plt.plot([2,3,4,5])
    ax.set_xlabel("$x$ /mm")
    ax.set_ylabel("$y$ /mm")
    plt.show()
    

    【讨论】:

      【解决方案3】:

      joaquin 的答案有效,但具有从轴左侧删除刻度的副作用。要解决此问题,请联系tick_right() 并致电set_ticks_position('both')。修改后的例子:

      from matplotlib import pyplot as plt
      
      f = plt.figure()
      ax = f.add_subplot(111)
      ax.yaxis.tick_right()
      ax.yaxis.set_ticks_position('both')
      plt.plot([2,3,4,5])
      plt.show()
      

      结果是一个两边都有刻度的图,但右边有刻度标签。

      【讨论】:

        【解决方案4】:

        只是有人问的情况(就像我做的那样),这在使用 subplot2grid 时也是可能的。例如:

        import matplotlib.pyplot as plt
        plt.subplot2grid((3,2), (0,1), rowspan=3)
        plt.plot([2,3,4,5])
        plt.tick_params(axis='y', which='both', labelleft='off', labelright='on')
        plt.show()
        

        它会显示这个:

        【讨论】:

        • 这也适用于ax.tick_params(axis='y', which='both', labelleft='off', labelright='on')。但它不会移动ylabel
        • 您可以随时使用plt.gca() 获取当前坐标区对象。因此你会使用:plt.gca().yaxis.set_label_position("right")
        • labelleft, labelright : bool。所以应该是plt.tick_params(axis='y', which='both', labelleft=False, labelright=True) 来禁用左侧标签。还有left=False, right=True 也可以移动刻度。
        猜你喜欢
        • 1970-01-01
        • 2020-05-11
        • 1970-01-01
        • 2021-10-29
        • 2014-07-13
        • 1970-01-01
        • 1970-01-01
        • 2020-12-16
        相关资源
        最近更新 更多