【问题标题】:How to plot a line plot with confidence intervals and legend changing over x-axis in python如何在python中绘制带有置信区间和图例在x轴上变化的线图
【发布时间】:2020-06-15 19:01:18
【问题描述】:

我有一个如下所示的数据框:

    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')

我想添加一个带有置信区间的阴影区域,因为它是根据 foo 数据框中的 top_cibottom_ci 列定义的。

有什么想法可以做到吗?

【问题讨论】:

  • 检查this answer 看看阴影来自哪里
  • 也许您可以使用seaborn,您甚至不必自己定义间隔。 “默认情况下,该图在每个 x 值处聚合多个 y 值,并显示集中趋势的估计值和该估计值的置信区间。”。但如果你想自己画,可以从source code of this function 获得灵感。

标签: python python-3.x seaborn


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    • 2016-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    相关资源
    最近更新 更多