Search code examples
pythonmatplotlibaxis-labels

How to manipulate the y-axis in matplotlib?


I am displaying a ratio in matplotlib with

plt.plot(datax, datay, style, color=colour)

However, I want the data below 1 to be displayed as 2-1/y. For example: A data point with the value 2 should be displayed at 2, a value 1 at 1 but a value 1/2 should be displayed where 0 would be, a value of 1/3 where -1 would be, 1/4 at -2 and so forth. However, I want the labels to show the actual value of the data point.


Solution

  • Assuming that you use scatter plot and datay is a numpy array, you can build another array of new Y coordinates:

    datay1 = np.where(datay < 1, 2 - 1 / datay, datay)
    

    And then plot the data points in the new positions, but annotate them with old labels:

    plt.scatter(datax, datay1)
    for x,y,y1 in zip(datax, datay, datay1):
        plt.annotate("%.f" % y, xy=(x,y1))