时间序列子图绘制求助:折线图与直方图样式调整问题
时间序列子图绘制问题处理
样本数据
使用的pd.DataFrame格式数据如下:
Price_REG1 Price_REG2 Price_REG3 Price_REG4 date 2020-01-01 00:00:00 30.83 30.83 30.83 30.83 2020-01-01 01:00:00 28.78 28.78 28.78 28.78 2020-01-01 02:00:00 28.45 28.45 28.45 28.45 2020-01-01 03:00:00 27.90 27.90 27.90 27.90 2020-01-01 04:00:00 27.52 27.52 27.52 27.52
1. 折线图:图例仅显示在最后一个子图
用户代码:
df.plot(subplots=True, color= ['grey', 'grey', 'grey', 'grey'], figsize=(6, 6),lw=0.8, xlabel='', legend=False) plt.legend(["AA", "BBB", "AAA", "BBB"]);
解决方法
plt.legend()默认仅给最后一个子图添加图例,需遍历所有子图单独设置:
axes = df.plot(subplots=True, color=['grey']*4, figsize=(6,6), lw=0.8, xlabel='', legend=False) labels = ["AA", "BBB", "AAA", "BBB"] for ax, label in zip(axes, labels): ax.legend([label])
2. 直方图1:修改标题+添加图例
用户代码:
fig, ax = plt.subplots(2, 2, sharex='col', sharey='row') m=0 for i in range(2): for j in range(2): df.hist(column = df.columns[m], grid=False, color='grey', bins = 150, ax=ax[i,j], figsize=(20, 20)) m+=1
需求与实现代码
- 替换默认标题为自定义标题(如"Price Region 1")
- 添加对应图例
fig, axs = plt.subplots(2, 2, sharex='col', sharey='row', figsize=(20,20)) custom_titles = ["Price Region 1", "Price Region 2", "Price Region 3", "Price Region 4"] custom_labels = ["AA", "BBB", "AAA", "BBB"] m = 0 for i in range(2): for j in range(2): # 获取直方图的patch对象用于创建图例 patches = df.hist(column=df.columns[m], grid=False, color='grey', bins=150, ax=axs[i,j])[0] # 设置自定义标题 axs[i,j].set_title(custom_titles[m]) # 添加图例 axs[i,j].legend([patches], [custom_labels[m]]) m += 1 plt.tight_layout()
3. 直方图2:移除Y轴标签+替换图例为自定义标题
用户代码:
fig, ax = df.plot(kind='hist', bins=150, subplots=True,sharex='col',sharey='row', title=False,layout=(2, 2), legend=True)
需求与实现代码
- 移除Y轴标签
- 去掉图例,添加自定义标题
custom_titles = ["Price Region 1", "Price Region 2", "Price Region 3", "Price Region 4"] axes = df.plot(kind='hist', bins=150, subplots=True, sharex='col', sharey='row', title=False, layout=(2,2), legend=False, figsize=(10,8)) # 遍历子图设置标题并清空Y轴标签 for ax, title in zip(axes.flatten(), custom_titles): ax.set_title(title) ax.set_ylabel('') plt.tight_layout()
内容的提问来源于stack exchange,提问作者user20050294
相关产品推荐
相关产品推荐

