如何让matplotlib/pylab中的X轴不自动排序值?
每次我画图的时候,X轴的数值会自动排序(比如说,如果我输入的数值是3、2、4,它会自动把X轴从小到大排序)。
我想知道怎么才能让X轴保持我输入的顺序,也就是3、2、4。
import pylab as pl
data = genfromtxt('myfile.dat')
pl.axis('auto')
pl.plot(data[:,1], data[:,0])
我找到一个函数,叫做set_autoscalex_on(FALSE),但是我不太确定怎么用,或者它是否能满足我的需求。谢谢!
2 个回答
3
也许你想设置一下 xticks
(x轴刻度):
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])
这是一个可以运行的示例:
另外一个选择是使用日期时间。如果你在处理日期的话,可以把这些日期作为输入来绘制图表。
这是另一个可以运行的示例:
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()
5
你可以提供一个虚假的x范围,然后再覆盖x轴的标签。我同意上面评论的观点,质疑这是否是最好的解决办法,但没有具体情况很难判断。
如果你真的想这样做,这可能是一个选择:
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)
补充:如果你在处理日期,为什么不直接在轴上绘制真实的日期呢?如果你想在轴上显示29、30、1、2等日期,可以考虑按月份的天数来格式化。