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

Matplotlib柱状图X轴时间刻度与柱状条对齐问题求助

解决Matplotlib柱状图X轴时间刻度与柱状条对齐问题

你的问题核心是直接用字符串时间作为x轴数据时,Matplotlib的刻度位置和柱状条没有精准对应。我们可以通过先以数值索引定位柱状条,再手动绑定时间标签的方式,既解决对齐问题,又保留原有的时间格式刻度。

修正后的完整代码

import matplotlib.pyplot as plt
import numpy as np

g01 = ['2021-02-01 05:00:31', '2021-02-02 00:01:04', '2021-02-03 00:05:09', '2021-02-04 00:05:15', '2021-02-05 00:03:14', '2021-02-06 00:00:25', '2021-02-07 00:04:09', '2021-02-08 00:04:35', '2021-02-09 00:00:00', '2021-02-10 00:02:00', '2021-02-11 00:01:28', '2021-02-12 00:06:31', '2021-02-13 00:00:30', '2021-02-14 00:03:30', '2021-02-15 00:05:20', '2021-02-16 00:00:13', '2021-02-17 00:00:21', '2021-02-18 00:08:02', '2021-02-19 00:00:31', '2021-02-20 00:00:04', '2021-02-21 00:05:05', '2021-02-22 00:02:18', '2021-02-23 00:00:10', '2021-02-24 00:00:38', '2021-02-25 00:00:47', '2021-02-26 00:00:17', '2021-02-27 00:00:28', '2021-02-28 00:03:00']
g02 = [164, 158, 180, 200, 177, 112, 97, 237, 95, 178, 163, 78, 67, 65, 134, 93, 220, 74, 131, 172, 77, 102, 208, 109, 113, 208, 110, 101]

fig, ax1 = plt.subplots(1,1)
plt.yscale("log")

# 生成数值型x轴位置,确保每个柱状条有明确的坐标点
x_pos = np.arange(len(g01))
barlist1 = ax1.bar(x_pos, g02)

# 设置前21个柱子为粉色
for i in range(21):
    barlist1[i].set_color('pink')

# 绑定刻度:用数值位置对齐柱子,标签用原时间字符串
plt.xticks(x_pos, g01, rotation=70)

plt.xlabel('period', fontsize=14, fontweight="bold")
plt.ylabel('rating values', fontsize=10, fontweight="bold")
plt.tight_layout()  # 自动调整布局,避免刻度被截断
plt.show()

关键修改说明

  • 用数值索引定位柱子:通过np.arange(len(g01))生成0到27的连续数值,作为每个柱状条的x坐标,让每个柱子的位置精准可控。
  • 手动绑定时间标签:plt.xticks(x_pos, g01)把每个数值位置对应的刻度标签替换为原时间字符串,既保证了刻度与柱子严格对齐,又保留了需要的时间格式。
  • 添加布局调整:plt.tight_layout()会自动调整图表边距,避免旋转后的时间刻度被图表边缘遮挡,提升可读性。

这样修改后,你的柱状图X轴时间刻度就会和每个柱状条的中心精准对齐,同时完全保留原有的时间格式啦。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 15:52:37