将NumPy数组转为Matplotlib的X/Y轴,解决时间轴与柱状图报错问题
解决方案
问题1:修正数组维度,解决柱状图类型错误
你当前切片得到的timestamp、prices、solar都是二维数组(形状为(n,1)),而Matplotlib的plt.bar和plt.plot需要一维数组作为输入,这是触发TypeError: only size-1 arrays can be converted to Python scalars的核心原因。
修正切片方式,直接提取一维数组:
import numpy as np import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter # 加载数据 combined_list = np.load('dumpert.npy', allow_pickle=True) # 提取一维数组(替代原切片逻辑) timestamp = combined_list[:, 0] # 直接取第0列,得到一维datetime数组 prices = combined_list[:, 1].astype(float) # 取第1列并转为float类型 solar = combined_list[:, 3].astype(int) # 取第3列并转为int类型
问题2:设置X轴为时间并显示小时格式
使用Matplotlib的DateFormatter来指定X轴时间显示格式为%H:%M(小时:分钟),同时自动旋转标签避免重叠:
# 创建画布和轴对象 fig, ax = plt.subplots() # 绘制价格柱状图 ax.bar(timestamp, prices, width=0.04, label='Price') # width设置为0.04适配小时级时间间隔 # 绘制功率折线图 ax.plot(timestamp, solar, color='orange', label='Solar Power') # 设置X轴时间格式 date_format = DateFormatter('%H:%M') ax.xaxis.set_major_formatter(date_format) # 自动旋转X轴标签,避免重叠 fig.autofmt_xdate() # 添加图例和标签 ax.set_xlabel('Time') ax.set_ylabel('Value') ax.legend() plt.show()
关键说明
- 切片时使用
[:, index]替代[0:rows+1, index:index+1],直接获取一维数组,避免维度不匹配问题。 width=0.04是因为Matplotlib中datetime类型的宽度单位是天,0.04天约等于57分钟,适配小时级的时间间隔,避免柱子重叠。DateFormatter('%H:%M')指定仅显示小时和分钟,若需要显示日期可调整格式字符串(如%m-%d %H:%M)。
内容的提问来源于stack exchange,提问作者Gabrie
相关产品推荐
相关产品推荐

