【发布时间】:2026-02-13 14:55:01
【问题描述】:
我想绘制一个条形图(或直方图,但不是其他图),使 x 值对应于时间段,但 x 轴标签是从 00:00 到 23:59,间隔为半小时。
问题出在我的数据框中:["Start Time"] 列中的值是 "datetime.time" 类型,看起来像
0 00:30:00
1 06:00:00
2 07:00:00
3 09:10:00
4 15:30:00
5 18:00:00
6 19:00:00
['Main Street Green (s)'] 是对应的值。例如:
0 NaN
1 13.5
2 25.5
3 50.5
4 55.5
5 20.5
6 38.5
我希望从 00:00 到 00:30 的条形高度为 0 从 00:30 到 06:00 的条形高度为 13.5 从 06:30 到 07:00 的酒吧高度为 25.5 ...
我看过很多线图。 https://www.programcreek.com/python/example/61484/matplotlib.dates.HourLocator 是我发现的最有价值的资源
plt.rcParams['figure.figsize'] = (8.0, 6.0)
ax = plt.subplot(111)
ax.plot(Dayton_weekday["Start Time"], Dayton_weekday['Main Street Green (s)'], color = 'blue', label="main street")
#set ticks every half an hour
ax.xaxis.set_major_locator(mdates.HourLocator(byhour=range(0,24,48)))
#set major ticks format
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))
ax.set_xlim(["00:00", "23:59"])
ax.set_ylim(bottom=0)
在我的代码中,我使用 ax.plot 那是因为如果我使用 ax.bar "ValueError: microsecond must be in 0..999999" 将被返回 所以我不知道如何使用我拥有的数据绘制条形图
【问题讨论】:
-
ax.plot.bar(Dayton_weekday['Start Time'], Daton_weekday['Main...']? -
那行不通。将返回错误“AttributeError: 'function' object has no attribute 'bar'”
标签: python-3.x datetime matplotlib