使用seaborn绘制平均值和95%CI值

2024-05-23 18:48:27 发布

您现在位置:Python中文网/ 问答频道 /正文

        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列中的数据绘制每一行。屈服值应表示为点,上下CI值应表示为方框图,类似于:

enter image description here

每种作物都应该用不同的颜色来表示,而每一年都应该用同一种作物的不同颜色来表示。有没有一种方法可以使用seaborn或matplotlib实现这一点


Tags: 数据作物cropci颜色绘制upperyear
1条回答
网友
1楼 · 发布于 2024-05-23 18:48:27

下面是一个使用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()

这是它产生的情节 enter image description here

相关问题 更多 >