import pandas as pd
import matplotlib.pyplot as plt
import os
# 读取 Excel 数据
file_path = r"E:\11.xlsx"
output_folder = r"E:\空间分布"
df = pd.read_excel(file_path)
# 确保输出目录存在
os.makedirs(output_folder, exist_ok=True)
# 计算 2000-2023 年均值和标准差
df_2000_2023 = df[(df["year"] >= 2011) & (df["year"] <= 2023)]
mean_2000_2023 = df_2000_2023.drop(columns=["year"]).mean()
std_2000_2023 = df_2000_2023.drop(columns=["year"]).std()
# 定义绘图函数
def plot_bar_with_error_and_labels(mean_values, std_values, output_file):
x_labels = mean_values.index # 草地类型
x = range(len(x_labels)) # X 轴坐标
plt.figure(figsize=(7, 5)) # 调整图形大小
bars = plt.bar(
x, mean_values, yerr=std_values, capsize=6, width=0.6,
color='#F8E7C0', edgecolor='black', linewidth=2, alpha=0.9, error_kw={'elinewidth': 2, 'ecolor': 'black'}
)
# 添加均值标签在柱子顶部(显示 4 位小数)
for i, (bar, value) in enumerate(zip(bars, mean_values)):
plt.text(
bar.get_x() + bar.get_width() / 2, bar.get_height() + std_values[i],
f'{value:.4f}', ha='center', va='bottom', fontsize=14, fontname='Arial'
)
# X 轴刻度和标签,确保和柱子对齐
plt.xticks(x, x_labels, rotation=0, ha='center', fontname='Arial', fontsize=14)
# 添加左侧 Y 轴标签
plt.ylabel("这里需要改(单位)", fontsize=14, fontname='SimHei')
plt.yticks(fontsize=12, fontname='Arial') # 设置 Y 轴刻度字体
# 设置轴线和刻度线的宽度一致
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_linewidth(1.5)
ax.spines['left'].set_linewidth(1.5)
# 设置刻度线宽度
plt.tick_params(axis='x', width=1.5) # 设置 X 轴刻度线宽度
plt.tick_params(axis='y', width=1.5) # 设置 Y 轴刻度线宽度
# 保存图像
plt.tight_layout()
plt.savefig(output_file, dpi=300, format='png', bbox_inches='tight', transparent=False) # 去除白边,背景不透明
plt.close()
# 绘制并保存 2000-2023 年的图
plot_bar_with_error_and_labels(
mean_2000_2023, std_2000_2023,
os.path.join(output_folder, "2011_2023_gpp_t.png")
)
print(f"图像已保存到 {output_folder}")