首页 > 解决方案 > 使用 seaborn 绘制均值和 95% CI 值

问题描述

        Region    Year   Crop          Yield     Lower CI     Upper CI
0    Argentina  2017.0   Soya    2770.885366  2647.711922  2937.259244
1    Argentina  2018.0   Soya    3442.598073  3375.280283  3512.806645
2    Argentina  2019.0   Soya    3472.638859  3415.621142  3536.144550
3    Argentina  2020.0   Maize   6203.009997  6020.164203  6387.457295

使用上面的数据框,我想使用 Yield、Lower CI 和 Upper CI 列中的数据绘制每一行。Yield 值应表示为一个点,而下 CI 值和上 CI 值应表示为箱形图,类似于:

在此处输入图像描述

每种作物应使用不同的颜色表示,而该作物的每年应使用相同颜色的不同阴影。有没有办法使用 seaborn 或 matplotlib 来做到这一点?

标签: pythonmatplotlibseaborn

解决方案


这是一个matplotlib可以帮助您入门的答案,然后您可以告诉我您还需要什么。请注意,根据您提供给我们的数据,情节并不那么有趣,因为没有一种作物有重叠的年份。到目前为止,不包括每年的不同色调(真的需要吗?)。

import matplotlib.pyplot as plt
from matplotlib import ticker

# Get the lower and upper "error bars"
df = df.assign(Lower=df["Yield"] - df["Lower CI"], Upper=df["Upper CI"] - df["Yield"])

# Make a new figure and axes
fig, ax = plt.subplots()

# Group the data by crop, and iterate through each crop
for crop, data in df.groupby("Crop"):
    ax.errorbar(
        data["Year"],
        data["Yield"],
        yerr=(data["Lower"], data["Upper"]),
        fmt="o",
        label=crop,
        capsize=5,
    )
ax.legend()
# This sets the x-axis to have ticks on years (so we don't get e.g. 2019.5)
ax.xaxis.set_major_locator(ticker.MultipleLocator())
ax.set(xlabel="Year", ylabel="Yield")
plt.show()

这是它产生的情节 在此处输入图像描述


推荐阅读