python - 使用 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 来做到这一点?
解决方案
这是一个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()
推荐阅读
- jolt - jolt - 将键从嵌套对象复制或移动到顶层
- tensorflow - 使用参数分层后类不平衡和性能下降
- python - 使用 selenium 和 python 实现 google 的自动化
- azure - 使用链接访问 Azure Data Lake Container
- phpoffice-phpspreadsheet - PHPSpreadSheet 无法找到电子表格中存在的“命名范围”
- powershell - 在日志文件中的连续行中搜索多个字符串
- php - 在 Halk Bank Payment Gateway For Woocommerce 中将订单总额转换为默认货币
- java - 如何摆脱招摇 ui 响应中的示例值
- css - Shinydashboard 侧边栏初学者问题——要点
- html - 只有一个出现在屏幕上的元素