【问题标题】:Set only positive xticks on a horizontal barplot在水平条形图上仅设置正 xticks
【发布时间】:2017-02-22 13:43:40
【问题描述】:

我想在水平条形图的 x 轴上设置正值,但我不知道该怎么做。

我的情节的一个小例子:

我想用 0 左边的 500 和 1000 替换 -500 和 -1000。

这里是我的代码,其中 y 和 y2 列出了值。

    y = [-i for i in y]
    plt.barh(range(1, len(y)+1), y, label="Serie_1")
    plt.barh(range(1, len(y2)+1), y2, alpha=0.5, color="r", label="Serie_2")
    plt.axvline(0, color="k")
    plt.yticks([i+1.5 for i in range(7)], range(7))
    plt.title("test")
    plt.legend()

我知道它与 xticks 相关,但如何?

【问题讨论】:

    标签: python matplotlib bar-chart axis-labels


    【解决方案1】:

    您可以在事后将标签文本替换为其绝对值:

    plt.gca().set_xticklabels([abs(x) for x in plt.gca().get_xticks()])
    

    【讨论】:

    • 哦,谢谢它有效!这么长的一条线。请注意,它返回浮点值,我只是放了一个“int()”来删除小数。
    【解决方案2】:

    更灵活的解决方案:使用plt.xticks。这是一个 MWE。

    import matplotlib.pylab as plt
    
    fig, ax = plt.subplots()
    
    x = range(-5, 5)
    y = range(-5, 5)
    
    plt.plot(x, y)
    plt.xticks(x, [abs(i) for i in x])
    plt.show()
    

    产生,

    【讨论】:

      猜你喜欢
      • 2019-10-13
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 2017-09-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多