python - 如何在python中绘制带有置信区间和图例在x轴上变化的线图
问题描述
我有一个看起来像这样的数据框:
import pandas as pd
foo = pd.DataFrame({'time':[1,2,3,4], 'value':[2,4,6,8], 'group':['a', 'a', 'b', 'b'],
'top_ci':[3,5,7,9], 'bottom_ci': [1,3,5,7]})
我想创建一个线图,所以我使用以下代码:
ax = sns.lineplot(x="time", y="value", hue="group", data=foo)
ax.figure.savefig('test.png', bbox_inches='tight')
我想添加一个带有置信区间的阴影区域,因为它是从数据框中的top_ci
和bottom_ci
列定义的foo
。
任何想法我怎么能做到这一点?
解决方案
最简单的方法是提供单个数据点,然后sns.lineplot
为您计算置信区间。如果您想/需要自己做,您可以使用ax.fill_between
:
foo = pd.DataFrame({'time':[1,2,3,4], 'value':[2,4,6,8], 'group':['a', 'a', 'b', 'b'],
'top_ci':[3,5,7,9], 'bottom_ci': [1,3,5,7]})
groups = set(foo["group"]) # get group levels to get the same hue order in both plots
f, ax = plt.subplots()
sbn.lineplot(x="time", y="value", hue="group", data=foo, ax=ax, hue_order=groups)
for group in groups:
ax.fill_between(x=foo.loc[foo["group"] == group, "time"],
y1=foo.loc[foo["group"] == group, "bottom_ci"],
y2=foo.loc[foo["group"] == group, "top_ci"], alpha=0.2)
f.savefig('test15.png', bbox_inches='tight')
推荐阅读
- python - Minizinc Python - 使用 .dzn 模块而不是实例模块
- c# - 如何制作可点击、透明、无边框的表单?
- android - 使用 Xamarin CrossMedia 插件从图库中选取图像会导致应用程序终止
- javascript - JS/TS 中有这种模式的名称吗?
- mysql - MySQL:将时间字符串转换为毫秒
- javascript - TypeScript:访问对象上未定义的键时返回的类型是错误的?
- python - 套接字主机名,无法获取 IP
- ios - 尝试在 iOS 设备中颤振运行时,获取 s6Runner11AppDelegateC11application
- java - 空对象引用上的 View.findViewById(int)' 存在问题
- import - Acumatica 导入方案 - 导入 AR 发票 - 失衡错误