You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将Matplotlib横轴标签从24小时制改12小时制时遇值错误

问题原因及解决方法

错误根源

你手动定义的x_labels列表里有两处语法错误:

  • '10am' '11am'之间缺少逗号,Python会把这两个字符串自动拼接成一个'10am11am'
  • '10pm' '11pm'之间同样缺少逗号,合并成了'10pm11pm'
    原本应该有24个标签,现在因为这两处合并,实际只有22个,和np.arange(len(inputs))生成的24个刻度位置不匹配,所以抛出了ValueError。

修正后的代码

补上缺失的逗号即可解决问题:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from datetime import timedelta, date   
    
inputs = data['datetime'].groupby(data['datetime'].dt.hour).count()

# 补上两处缺失的逗号
x_labels = ['12am','1am', '2am', '3am', '4am', '5am', '6am', '7am', '8am', '9am', '10am', '11am',
           '12pm', '1pm', '2pm', '3pm', '4pm', '5pm', '6pm', '7pm', '8pm', '9pm', '10pm', '11pm']

fig, ax = plt.subplots(1, 1)

ax.plot(inputs)

plt.title('UFO Sightings by Hour of Day', fontweight='bold', fontsize=15)
ax.set_xlabel('Hour of Day')
ax.set_ylabel('UFO Sightings Reported')

ax.set_xticks(np.arange(len(inputs)), labels=x_labels)

plt.margins(0.001)
plt.tight_layout()
plt.show()

更省心的标签生成方式(避免手动出错)

不用逐个手动输入标签,可以借助datetime模块自动生成12小时制带AM/PM的标签,既高效又不会出错:

# 自动生成24小时对应的12小时制标签
x_labels = []
for hour in range(24):
    dt = pd.to_datetime(f'{hour}:00', format='%H:%M')
    # 格式化为12小时制,去掉前导0并转小写
    x_labels.append(dt.strftime('%I%p').lower().lstrip('0'))

生成的x_labels会自动匹配['12am', '1am', '2am', ..., '11pm']的格式,完全符合需求。

内容的提问来源于stack exchange,提问作者Exquisite_Poupon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 06:31:14