如何在Python同图中绘制以2019-2022为X轴的df1柱状图与df2折线图?
可行!实现年度柱状图+月度背景折线图的方案
完全可以实现,核心是处理好时间轴对齐和图层顺序,以下是具体步骤和代码示例:
1. 数据预处理
首先需要将两个DataFrame调整为适合绘图的格式:
- 把df2的
Month列转换为datetime类型,确保时间序列有序 - 将df1的宽格式(年度列)转为长格式,同时为年度数据匹配到时间轴上的对应位置(比如年度中点月份)
2. 代码实现
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import numpy as np # 模拟示例数据(替换为你的真实数据) df1 = pd.DataFrame({ 'County': ['A', 'B', 'C'], '2019': [100, 150, 200], '2020': [120, 160, 210], '2021': [130, 170, 220], '2022': [140, 180, 230] }) df2 = pd.DataFrame({ 'Month': pd.date_range(start='2019-01-01', end='2022-12-31', freq='M'), 'Value': np.random.randint(50, 100, size=48) }) # 预处理df1:转长格式+匹配年度中点时间 df1_long = df1.melt(id_vars='County', var_name='Year', value_name='Annual_Value') df1_long['Year'] = pd.to_datetime(df1_long['Year'], format='%Y') # 计算年度中点月份(用于在月度时间轴上定位柱子) df1_long['Mid_Month'] = df1_long['Year'] + pd.DateOffset(months=5.5) # 预处理df2:确保时间列是datetime df2['Month'] = pd.to_datetime(df2['Month']) # 绘图 fig, ax = plt.subplots(figsize=(12, 6)) # 先画背景折线图(df2月度数据) sns.lineplot(data=df2, x='Month', y='Value', ax=ax, color='#87CEEB', alpha=0.6, linewidth=2, label='月度数据') # 再画前景柱状图(df1年度数据) sns.barplot(data=df1_long, x='Mid_Month', y='Annual_Value', hue='County', ax=ax, alpha=0.8, width=30) # 调整X轴显示 ax.xaxis.set_major_formatter(plt.matplotlib.dates.DateFormatter('%Y-%m')) plt.xticks(rotation=45) # 设置标签和标题 ax.set_xlabel('时间(2019-2022)') ax.set_ylabel('数值') ax.set_title('年度区县数据柱状图与月度数据折线图叠加') plt.tight_layout() plt.show()
关键注意事项
- 图层顺序:先绘制折线图作为背景,再绘制柱状图作为前景,通过
alpha参数调整透明度,避免遮挡 - 时间对齐:年度数据通过
Mid_Month定位到年度中点,确保柱子在时间轴上的位置合理 - 柱子宽度:由于X轴是月度时间刻度,设置
width=30(对应天数)让柱子适配时间轴的间距 - 数据格式:务必将时间列转为datetime类型,否则matplotlib无法正确识别时间序列
内容的提问来源于stack exchange,提问作者Makayla Lawrence
相关产品推荐
相关产品推荐

