首页 > 解决方案 > 如何在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_cibottom_ci列定义的foo

任何想法我怎么能做到这一点?

标签: pythonpython-3.xseaborn

解决方案


最简单的方法是提供单个数据点,然后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')

在此处输入图像描述


推荐阅读