# How to make X axis in matplotlib/pylab to NOT sort automatically the values?

### Question

Whenever I plot, the X axis sorts automatically (for example, if i enter values 3, 2, 4, it will automatically sort the X axis from smaller to larger.

How can I do it so the axis remains with the order I input the values i.e 3, 2, 4

``````   import pylab as pl
data = genfromtxt('myfile.dat')
pl.axis('auto')
pl.plot(data[:,1], data[:,0])
``````

I found one function, set_autoscalex_on(FALSE) but I'm not sure how to use it or whether it is what I want. Thanks

1
9
2/8/2013 10:13:43 AM

You could provide a dummy x-range, and then override the xtick labels. I do agree with the comments above questioning wether its the best solution, but thats hard to judge without any context.

If you really want to, this might be an option:

``````fig, ax = plt.subplots(1,2, figsize=(10,4))

x = [2,4,3,6,1,7]
y = [1,2,3,4,5,6]

ax.plot(x, y)

ax.plot(np.arange(len(x)), y)
ax.set_xticklabels(x)
`````` edit: If you work with dates, why not plot the real date on the axis (and perhaps format it by the day-of-month if you do want 29 30 1 2 etc on the axis?

4
2/8/2013 10:41:23 AM

Maybe you want to set the `xticks`:

``````import pylab as pl
data = genfromtxt('myfile.dat')
pl.axis('auto')
xs = pl.arange(data.shape)
pl.plot(xs, data[:,0])
pl.xticks(xs, data[:,1])
``````

Working sample:

Another option would be to work with datetimes. If you work with dates, you can use those as input to the plot command.

Working sample:

``````import random
import pylab as plt
import datetime
from matplotlib.dates import  DateFormatter, DayLocator

fig, ax = plt.subplots(2,1, figsize=(6,8))

# Sample 1: use xticks
days = [29,30,31,1,2,3,4,5]
values = [random.random() for x in days]

xs = range(len(days))

plt.axes(ax)
plt.plot(xs, values)
plt.xticks(xs, days)

# Sample 2: Work with dates
date_strings = ["2013-01-30",
"2013-01-31",
"2013-02-01",
"2013-02-02",
"2013-02-03"]

dates = [datetime.datetime.strptime(x, "%Y-%m-%d") for x in date_strings]
values = [random.random() for x in dates]

plt.axes(ax)
plt.plot(dates,values)
ax.xaxis.set_major_formatter(DateFormatter("%b %d"))
ax.xaxis.set_major_locator(DayLocator())
plt.show()
`````` 