Advertisement
Advertisement


Reverse Y-Axis in PyPlot


Question

I have a scatter plot graph with a bunch of random x, y coordinates. Currently the Y-Axis starts at 0 and goes up to the max value. I would like the Y-Axis to start at the max value and go up to 0.

points = [(10,5), (5,11), (24,13), (7,8)]    
x_arr = []
y_arr = []
for x,y in points:
    x_arr.append(x)
    y_arr.append(y)
plt.scatter(x_arr,y_arr)
2016/04/11
1
273
4/11/2016 5:19:59 PM

Accepted Answer

There is a new API that makes this even simpler.

plt.gca().invert_xaxis()

and/or

plt.gca().invert_yaxis()
2011/11/26
573
11/26/2011 6:12:42 PM

DisplacedAussie's answer is correct, but usually a shorter method is just to reverse the single axis in question:

plt.scatter(x_arr, y_arr)
ax = plt.gca()
ax.set_ylim(ax.get_ylim()[::-1])

where the gca() function returns the current Axes instance and the [::-1] reverses the list.

2017/05/23

Use matplotlib.pyplot.axis()

axis([xmin, xmax, ymin, ymax])

So you could add something like this at the end:

plt.axis([min(x_arr), max(x_arr), max(y_arr), 0])

Although you might want padding at each end so that the extreme points don't sit on the border.

2010/01/12

If you're in ipython in pylab mode, then

plt.gca().invert_yaxis()
show()

the show() is required to make it update the current figure.

2013/10/25

You could also use function exposed by the axes object of the scatter plot

scatter = plt.scatter(x, y)
ax = scatter.axes
ax.invert_xaxis()
ax.invert_yaxis()
2019/07/03

Another similar method to those described above is to use plt.ylim for example:

plt.ylim(max(y_array), min(y_array))

This method works for me when I'm attempting to compound multiple datasets on Y1 and/or Y2

2015/05/27

Source: https://stackoverflow.com/questions/2051744
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]