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

多日重复小时数据绘图:X轴自定义显示问题求助

解决方法

首先先修正你代码里的几个基础问题:没导入matplotlib.pyplot、变量名和CSV列不匹配(比如用了fig.hr对应CSV的hour列,fig.kp_index对应S列等),然后分两种方案实现你要的X轴格式:

方案1:X轴显示小时(0、12、23循环格式)

直接基于现有hour列设置X轴刻度,只保留关键时间点标签避免重叠:

import pandas as pd
import matplotlib.pyplot as plt

# 读取数据,修正变量名和CSV列对应
fig = pd.read_csv('figt.csv')
y1 = fig['S']
y2 = fig['d']
fo = 8

figure, axs = plt.subplots(2, figsize=(10, 7), sharex=True)

# 用数据索引作为绘图的x轴位置,后续替换标签
axs[1].bar(range(len(fig)), y1, width=0.5)
axs[1].set_ylabel("S index", fontsize=fo)
axs[1].set_yticks([0, 50, 100])

axs[0].plot(range(len(fig)), y2)
axs[0].set_ylabel("B", fontsize=fo)
axs[0].set_yticks([-10, 0, 10])

# 筛选每天0、12、23点对应的索引作为刻度位置
tick_positions = fig.index[(fig['hour'] == 0) | (fig['hour'] == 12) | (fig['hour'] == 23)]
# 对应小时作为刻度标签
tick_labels = fig['hour'].iloc[tick_positions].astype(str)

axs[1].set_xticks(tick_positions)
axs[1].set_xticklabels(tick_labels)

plt.tight_layout()
plt.show()

如果希望每个小时都显示标签,直接替换成下面两行即可(数据量大时建议加旋转避免重叠):

axs[1].set_xticks(range(len(fig)))
axs[1].set_xticklabels(fig['hour'].astype(str), rotation=45)

方案2:X轴显示日期格式(如28-Oct)

先把year+day number(儒略日)转换成实际日期,再结合hour生成完整时间序列,用这个序列作为X轴:

import pandas as pd
import matplotlib.pyplot as plt

fig = pd.read_csv('figt.csv')
# 将儒略日转换为日期:year+day number → 年月日
fig['date'] = pd.to_datetime(fig['year'].astype(str) + fig['day number'].astype(str), format='%Y%j')
# 拼接hour生成完整的datetime
fig['datetime'] = fig['date'] + pd.to_timedelta(fig['hour'], unit='h')

y1 = fig['S']
y2 = fig['d']
fo = 8

figure, axs = plt.subplots(2, figsize=(10, 7), sharex=True)

# 用datetime作为x轴绘图
axs[1].bar(fig['datetime'], y1, width=0.1)  # width设为0.1对应2.4小时,贴合小时级数据
axs[1].set_ylabel("S index", fontsize=fo)
axs[1].set_yticks([0, 50, 100])

axs[0].plot(fig['datetime'], y2)
axs[0].set_ylabel("B", fontsize=fo)
axs[0].set_yticks([-10, 0, 10])

# 旋转日期标签避免重叠
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

关键说明:

  • 儒略日转换用format='%Y%j',其中%j代表一年中的第几天(001-366)
  • 条形图的width需要调整,因为datetime轴的单位是天,0.1对应2.4小时,更适配小时级数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 10:42:37