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

前端 未结 2 1211
忘了有多久
忘了有多久 2021-01-04 08:47

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

2条回答
  •  清歌不尽
    2021-01-04 09:32

    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[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 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?

提交回复
热议问题