Search code examples
pythonmatplotlibbar-chartaxis-labels

Set only positive xticks on a horizontal barplot


I would like to set positives values on the x axis on a horizontal barplot, but I don't know how to do.

A little example of my plot : enter image description here

I would like to replace -500 and -1000 with 500 and 1000 on the left of 0.

And here my code, with y and y2 lists with values.

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

I know that it's with xticks, but how ?


Solution

  • You can replace the label texts after the fact with their absolute values:

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