Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce Matplotlib plot with x-axis out of order?

I want to plot some y-data with an x-axis that does not appear in numerical order:

For example:

y = [100, 99, 93, 88, 85, 43]
x = [0, 5, 4, 3, 2, 1]
plot(x, y)

I'd like the x-axis to show up as 0, 5, 4, 3, 2, 1, in that order, evenly spaced, with the appropriate y values above.

How can I do this?

like image 320
OregonTrail Avatar asked Mar 10 '13 06:03

OregonTrail


People also ask

How do I flip the X-axis in Matplotlib?

Most common method is by using invert_xaxis() and invert_yaxis() for the axes objects. Other than that we can also use xlim() and ylim(), and axis() methods for the pyplot object. To invert X-axis and Y-axis, we can use invert_xaxis() and invert_yaxis() function.

How do I change the X-axis values in Matplotlib?

The xticks() function in pyplot module of the Matplotlib library is used to set x-axis values. List of xticks locations. Passing an empty list will remove all the xticks.

How do I change the order of items in Matplotlib legend?

Change order of items in the legend The above order of elements in the legend region can be changed by the gca method that uses another sub-method called get_legend_handles_labels method. These handles and labels lists are passed as parameters to legend method with order of indexes.


1 Answers

I'd use the x 'values' as the xtick labels instead. For example:

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
y = [100, 99, 93, 88, 85, 43]
xt = [0, 5, 4, 3, 2, 1]
ax.plot(y)
ax.set_xticklabels(xt)
fig.savefig("out.png")

produces

pic with changed xtick labels

More generally, you could set the x coordinates to be whatever you wanted, and then set xticks and xticklabels appropriately.

like image 65
DSM Avatar answered Sep 27 '22 20:09

DSM