如何在Matplotlib中对齐柱状图与阶梯折线图的X轴
解决Matplotlib柱状图与阶梯折线图X轴对齐问题
问题核心:柱状图的每个柱子对应时段区间(如00:00-01:00),阶梯折线图的水平线段也应覆盖相同区间,但原代码使用字符串作为X轴分类变量,导致柱子中心与阶梯线段的位置不匹配。
关键修改思路
- 使用数值型索引作为X轴底层坐标,精确控制柱子和阶梯的位置
- 设置柱状图宽度为1,让每个柱子刚好占据两个相邻索引之间的区间
- 调整X轴范围,确保最后一个时段的阶梯线段完整显示
- 将数值索引替换为时间字符串作为刻度标签
修改后的完整代码
import matplotlib.pyplot as plt import numpy as np # Time of day values time_of_day = [ "00:00", "01:00", "02:00", "03:00", "04:00", "05:00", "06:00", "07:00", "08:00", "09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00" ] # Electricity load values in W electricity_load = np.array([ 5460, 177, 163, 745, 770, 1049, 1090, 868, 277, 3117, 3416, 1383, 1551, 4324, 969, 431, 703, 1201, 898, 4969,7839, 259, 410, 617 ]) # Convert electricity load values to kW electricity_load_kW = electricity_load / 1000 # Price values in Cent/kWh price_values = [ 27.1, 26.5, 26.0, 25.1, 26.6, 27.5, 34.4, 51.3, 45.3, 44.3, 44.3, 41.3, 38.1, 35.5, 33.9, 37, 41.4, 48.6, 53.4, 48.6, 43.4, 38.7, 37.8, 27.4, ] # 创建数值型X轴索引,对应每个时段的左端点 x = np.arange(len(time_of_day)) # Create subplots within the same figure fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 10), sharex=True) # 绘制柱状图:width=1,让柱子刚好占据x到x+1的区间 ax1.bar(x, electricity_load_kW, width=1, color='#FFD700', edgecolor='black') # Labeling the first plot ax1.set_ylabel('Electricity Load (kW)', fontsize=18) ax1.grid(axis='y', linestyle='--', alpha=0.7) # 绘制阶梯图:where='post'表示从当前x位置延伸到下一个x位置 ax2.step(x, price_values, where='post', color='limegreen', linewidth=6) # Labeling the second plot ax2.set_xlabel('Time of Day', fontsize=18) ax2.set_ylabel('Price (Cent/kWh)', fontsize=18) ax2.grid(axis='y', linestyle='--', alpha=0.7) # 调整X轴范围,确保最后一个时段(23:00-00:00)的阶梯线段完整显示 ax1.set_xlim(-0.1, x[-1]+1.1) # 设置X轴刻度:将数值索引替换为时间字符串,刻度位置对应时段左端点 ax2.set_xticks(x) ax2.set_xticklabels(time_of_day) # Increase thickness and rotation of x-tick labels for ax in [ax1, ax2]: ax.tick_params(axis='x', which='both', labelsize=14, width=2) # Set x-tick labels with rotation and horizontal alignment plt.sca(ax2) plt.xticks(rotation=45, ha='right') # Tighten the layout plt.tight_layout() # Save the figure and plot it plt.savefig('C:/Users/wi9632/Desktop/temp_combined.png', dpi=100) plt.show()
修改点说明
- 新增
x = np.arange(len(time_of_day)):用0-23的数值索引代表每个时段的左端点 ax1.bar(x, ..., width=1):柱子宽度设为1,刚好覆盖x到x+1的区间,对应一个小时的时段ax1.set_xlim(-0.1, x[-1]+1.1):扩展X轴范围,避免最后一个柱子和阶梯线段被截断ax2.set_xticks(x)和ax2.set_xticklabels(time_of_day):将数值刻度替换为时间字符串,保证显示的标签和实际区间对应
这样修改后,柱状图的左右边界会和阶梯折线图的水平线段完全对齐,每个时间区间(如00:00-01:00)的视觉位置完全匹配。
内容的提问来源于stack exchange,提问作者PeterBe
相关产品推荐
相关产品推荐

