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

月度历史均值与2023年实际值的相关性分析及可视化求助

相关性分析与堆叠柱状图+相关性折线图实现

1. 相关性计算结果

2019-2022年月度均值与2023年对应月份实际值(1-4月)的皮尔逊相关系数为0.9895(约0.99),表明两者存在极强的正线性相关关系。

2. Python实现代码

以下代码会完成相关性计算,并生成所需的堆叠柱状图,同时叠加均值、实际值折线以及相关性回归嵌入图:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import linregress

# 将提供的数据加载到DataFrame中
data = {
    'Year': ['2019', '2020', '2021', '2022', '2023', 'Average'],
    'Jan': [10, 7, 56, 55, 20, 32],
    'Feb': [15, 14, 51, 61, 23, 35.25],
    'Mar': [20, 28, 3, 34, 12, 21.25],
    'Apr': [25, 14, 30, 44, 16, 28.25]
}
df = pd.DataFrame(data).set_index('Year')

# 提取相关数据集
historical_data = df.loc[['2019', '2020', '2021', '2022']]
monthly_avg = df.loc['Average']
actual_2023 = df.loc['2023']

# 计算皮尔逊相关系数
correlation, _ = np.corrcoef(monthly_avg, actual_2023)
correlation = correlation[0][1]
print(f"皮尔逊相关系数: {correlation:.4f}")

# 生成可视化图表
fig, ax_main = plt.subplots(figsize=(12, 7))
months = monthly_avg.index
x = np.arange(len(months))
bar_width = 0.6

# 创建2019-2022年数据的堆叠柱状图
bottom = np.zeros(len(months))
for year in historical_data.index:
    ax_main.bar(x, historical_data.loc[year], bar_width, label=f'{year}年', bottom=bottom)
    bottom += historical_data.loc[year]

# 叠加历史均值和2023实际值的折线
ax_main.plot(x, monthly_avg, marker='o', color='black', linewidth=2, label='2019-2022月度均值')
ax_main.plot(x, actual_2023, marker='s', color='red', linewidth=2, label='2023实际值')

# 添加带相关性回归线的嵌入散点图
ax_inset = fig.add_axes([0.72, 0.2, 0.25, 0.25])
slope, intercept, _, _, _ = linregress(monthly_avg, actual_2023)
regression_line = slope * monthly_avg + intercept

ax_inset.scatter(monthly_avg, actual_2023, color='darkblue', s=50)
ax_inset.plot(monthly_avg, regression_line, color='darkred', label=f'r = {correlation:.2f}')
ax_inset.set_xlabel('历史均值')
ax_inset.set_ylabel('2023实际值')
ax_inset.legend()

# 格式化主图表
ax_main.set_xlabel('月份', fontsize=12)
ax_main.set_ylabel('数值', fontsize=12)
ax_main.set_title('月度数据(2019-2022堆叠柱状图)vs 2023实际值与历史均值', fontsize=14)
ax_main.set_xticks(x)
ax_main.set_xticklabels(months)
ax_main.legend(loc='upper left', bbox_to_anchor=(1, 1), fontsize=10)

plt.tight_layout()
plt.show()

3. 图表说明

  • 堆叠柱状图: 展示2019-2022年每个月份的各年度数据,直观呈现月度累计值及年度间的数值分布。
  • 黑色折线: 代表2019-2022年各月份的平均数值。
  • 红色折线: 绘制2023年对应月份的实际数值。
  • 嵌入散点图: 展示历史月度均值与2023实际值的直接关联,回归线突出两者极强的正相关性(r≈0.99)。

内容的提问来源于stack exchange,提问作者Ethan Altmayer

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:12:08