如何在python matplotlib中获得沿x轴的指示顺序

时间:2017-11-17 07:46:58

标签: python matplotlib

我想沿x轴以所需的顺序绘制点 - 例如'2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4 ',' 2017-11-01-5',。但plot函数会将顺序更改为按字母顺序排列 - '2017-11-01-1', '2017-11-01-2', '2017-11-01-3', '2017-11-01-4 ',' 2017-11-01-5'

是否可以按照我需要的顺序沿x轴绘制点?

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
x = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5'] # the order I need
y = ['1879994', '1879995', '1891647', '1889925', '1879900']

xax = ax.get_xaxis()

plt.title('Title')
plt.ylabel('PPS')
plt.xlabel('Date-Commit')
xlabels = xax.get_ticklabels()

for label in xlabels:
    label.set_rotation(45)

ax.plot(x, y, '-bo')
plt.savefig('chart.png', fmt='png')
plt.show()

received chart

1 个答案:

答案 0 :(得分:0)

尝试使用虚拟x轴并使用所需的日期作为xticklabels

import matplotlib.pyplot as plt

y = [1879994, 1879995, 1891647, 1889925, 1879900]
x = range(len(y))
ticklabels = ['2017-11-01-2', '2017-11-01-3', '2017-11-01-1', '2017-11-01-4', '2017-11-01-5']
plt.xticks(x, ticklabels)
plt.plot(x, y)
plt.show()