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

Whenever I draw, the X axis is sorted automatically (for example, if I enter the values โ€‹โ€‹3, 2, 4, it automatically sorts the X axis from smaller to larger.

How can I do this so that the axis stays in the order of input values โ€‹โ€‹ie 3, 2, 4

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

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

+4
source share
2 answers

You can provide a dummy x-range, and then override the xtick shortcuts. I agree with the comments above to talk about my best solution, but this is hard to judge without any context.

If you really want this, this could 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[0].plot(x, y) ax[1].plot(np.arange(len(x)), y) ax[1].set_xticklabels(x) 

enter image description here

edit: If you work with dates, why not build a real date on the axis (and maybe format it by the day of the month if you want 29 30 1 2, etc. on the axis?

+4
source

Maybe you want to install xticks :

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

Working example:

Another option is to work with dates. If you work with dates, you can use them as input to the plot command.

Working example:

 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[0]) 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[1]) plt.plot(dates,values) ax[1].xaxis.set_major_formatter(DateFormatter("%b %d")) ax[1].xaxis.set_major_locator(DayLocator()) plt.show() 

Sample

+2
source

All Articles