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

如何修改Python折线图X轴起始值,从指定时间(如17点)开始?

调整折线图X轴起始为17点的解决方案

数据集

Hour_day   Profits
  7          645
  3          354
  5          346
  11         153
  23         478
  7          464
  12         356
  0          346

需求说明

现有代码可正常绘制以Hour_day为X轴、Profits均值为Y轴的折线图,但当前X轴从0开始,需将X轴起始值改为17点(下午5点)。

原代码

hours = df.Hour_day.value_counts().keys()
hours = hours.sort_values() 

# 获取实际数据的绘图信息
y_values = list()
for hr in hours:
    temp = df[df.Hour_day == hr]
    y_values.append(temp.Profits.mean())
    
# 绘制对比图
plt.plot(hours, y_values, color='y')

修改方案

核心思路是重新调整X轴的小时顺序:先展示17点到23点的小时,再展示0点到16点的小时,同时对应调整Profits均值的顺序。

修改后的代码:

# 获取数据中所有唯一的小时并排序
existing_hours = sorted(df.Hour_day.unique())

# 重新排序小时:先放17-23区间的小时,再放0-16区间的小时
sorted_hours = [hr for hr in existing_hours if hr >= 17] + [hr for hr in existing_hours if hr < 17]

# 按新顺序提取对应小时的Profits均值
y_values = [df[df.Hour_day == hr].Profits.mean() for hr in sorted_hours]

# 绘制折线图
plt.plot(sorted_hours, y_values, color='y')
# 设置X轴刻度显示所有小时
plt.xticks(sorted_hours)
plt.xlabel('一天中的小时')
plt.ylabel('平均利润')
plt.show()

补充说明

如果需要强制X轴从17点开始显示(即使该时段无数据),可添加plt.xlim(left=17),但这会隐藏17点之前的小时数据。如果希望完整展示所有数据且起始为17点,上述调整顺序的方式更合适。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:15:40