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

如何使用Matplotlib与DataFrame绘制以time1为X轴的阶梯图?

解决步骤与修正代码

先梳理你代码里的几个问题:

  • num_t变量未定义,实际上price_energy的长度是96(24小时×4个15分钟时段),直接用len(price_energy)生成time1即可
  • 创建DataFrame时,你连续两次赋值df,第二次覆盖了第一次的price_energy数据,应该把两个列表合并成一个包含两列的DataFrame
  • 最后用Matplotlib或Pandas的绘图接口就能实现阶梯图绘制

以下是修正后的完整代码:

import pandas as pd
import matplotlib.pyplot as plt

energy_price = [33.28, 30.00, 29.15, 28.49, 34.66, 50.01,
               71.52, 77.94, 81.97, 87.90, 92.76, 94.98,
               92.31, 90.03, 90.09, 87.44, 85.37, 79.97,
               79.92, 77.83, 76.28, 65.06, 53.07, 34.16]
rtn_t0 = 15

# 生成price_energy列表
price_energy = []
for price in energy_price:
    price_energy += [int(price)] * int(60 / rtn_t0)

# 生成time1列表,直接匹配price_energy的长度
time1 = list(range(1, len(price_energy) + 1))

# 创建包含两列的DataFrame,指定列名方便后续操作
df = pd.DataFrame({
    'time': time1,
    'price_energy': price_energy
})

# 方法1:用Matplotlib原生绘制阶梯图
plt.figure(figsize=(12, 6))
plt.step(df['time'], df['price_energy'], where='post', label='Energy Price')
plt.xlabel('Time Slot')
plt.ylabel('Energy Price')
plt.title('Hourly Energy Price (15-Minute Intervals)')
plt.legend()
plt.grid(True)
plt.show()

# 方法2:用Pandas绘图接口更简洁
df.plot(x='time', y='price_energy', kind='step', where='post', figsize=(12, 6),
        xlabel='Time Slot', ylabel='Energy Price', title='Hourly Energy Price (15-Minute Intervals)')
plt.grid(True)
plt.show()

关键细节说明:

  • where='post'参数表示阶梯在每个时间点之后切换价格,符合你按15分钟时段定价的逻辑;如果需要在时间点前切换,改成where='pre'即可
  • 给DataFrame指定列名能让代码逻辑更清晰,避免后续操作时混淆数据
  • 代码开头的import语句是必须的,原代码里遗漏了这部分依赖导入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 15:45:42