Python设置xticks(希望它是0:00-1:00,1:00-2:00,...)

时间:2014-12-09 20:38:55

标签: python datetime matplotlib

我想将我的情节的x-tick设置为0:00-1:001:00-2:00,... 23:00-0:00,而不是原来的0, 1, 2, ..., 23

所以我用过:

plt.xticks(['0:00-1:00', '1:00-2:00', '2:00-3:00', '3:00-4:00', '4:00-5:00', '5:00-6:00', '6:00-7:00', '7:00-8:00',
            '8:00-9:00', '9:00-10:00', '10:00-11:00', '11:00-12:00', '12:00-13:00', '13:00-14:00', '14:00-15:00',
            '15:00-16:00', '16:00-17:00', '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00',
            '22:00-23:00', '23:00-24:00'])

但我收到了这个错误:

ValueError: invalid literal for float(): 9:00-10:00

那么我怎样才能实现目标呢?有什么建议?

1 个答案:

答案 0 :(得分:0)

您的代码无效的原因是您在xticks中直接使用字符串。您应该创建一个列表(在我的示例中为labels),然后将其作为参数分配给您的xticks

示例代码

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0,10,5)
y = np.sin(x)

labels = ['0:00-1:00', '1:00-2:00', '2:00-3:00', '3:00-4:00', '4:00-5:00'] # My manual xticks

plt.scatter(x,y)
plt.xticks(x,labels') # Here we assign it to xticks 
                      # Rotate them using "rotation='vertical'"
plt.show()

enter image description here