Skip to main content
 首页 » 编程设计

python之如何均匀设置有限数量的标签matplotlib python

2025年05月04日9lonelyxmas

我有一个这样的图表,它记录了 21 天的每小时数据,标签如下: 01-30 00:00、01-30 01:00....现在它们不可读了,所以我想每天只设置一个标签,所以只显示每天的第一个标签:01-30 00:00、01-31 00:00等

我的代码是:

fig1 = plt.figure()   
ax = fig1.add_subplot(111) 
ind = np.arange(len(timelist)) 
ax.bar(ind,reqlist,color='b') 
ax.set_xlim((0,len(timelist))) 
ax.set_ylabel('Number of request/video',size='x-large') 
ax.set_title('Request per hour North',size='xx-large') 
ax.set_xticks(ind) 
ax.set_xticklabels(timelist,rotation=17) 

时间列表是一个字符串列表:["01-30 00:00", "01-30 00:01".....]

请您参考如下方法:

你可以尝试只给你想要的标签,其余的给一个空字符串。
例如,如果您只需要每 24 天(一天)的标签:

newlist = [] 
for index, item in enumerate(timelist): 
    if index % 24 == 0: 
        newlist.append(item) 
    else: 
        newlist.append('') 
ax.set_xticklabels(newlist, rotation=17)