How to invert the x or y axis


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:
Asked By: DarkAnt



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.

Answered By: DisplacedAussie

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

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

Answered By: Tim Whitcomb

There is a new API that makes this even simpler.



Answered By: Demitri

If you’re in ipython in pylab mode, then


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

Answered By:

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

Answered By: Mortsde

Alternatively, you can use the matplotlib.pyplot.axis() function, which allows you inverting any of the plot axis

ax = matplotlib.pyplot.axis()

Or if you prefer to only reverse the X-axis, then


Indeed, you can invert both axis:

Answered By: Luis DG

using ylim() might be the best approach for your purpose:

xValues = list(range(10))
quads = [x** 2 for x in xValues]
plt.ylim(max(quads), 0)
plt.plot(xValues, quads)

will result:enter image description here

Answered By: Farzad Vertigo

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

scatter = plt.scatter(x, y)
ax = scatter.axes
Answered By: ShikharDua

If using matplotlib you can try:

matplotlib.pyplot.xlim(l, r)
matplotlib.pyplot.ylim(b, t)

These two lines set the limits of the x and y axes respectively. For the x axis, the first argument l sets the left most value, and the second argument r sets the right most value. For the y axis, the first argument b sets the bottom most value, and the second argument t sets the top most value.

Answered By: Andy Turner

if you are doing this in a subplot, here is the solution i found

fig, ax = plt.subplots(1,2, sharex = True)
for i in range(2):
    ax[i].plot(xdata, ydata)
axs = plt.gca()

While using sharex, last two lines needs to be outside the for loop

Answered By: oliveirals
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.