0

I have a dataframe that looks like this:

    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]})

I would like to create a lineplot, so i am using the following code:

  ax = sns.lineplot(x="time", y="value", hue="group", data=foo)
  ax.figure.savefig('test.png', bbox_inches='tight')

I would like to add a shaded area with the confidence interval, as it is defined from the top_ci and the bottom_ci columns in the foo dataframe.

Any ideas how I could do that ?

quant
  • 3,328
  • 1
  • 21
  • 49
  • Check [this answer](https://stackoverflow.com/a/53537206/5612363) to see where the shade comes from – Anwarvic Jun 15 '20 at 10:44
  • Maybe you could use [seaborn](https://seaborn.pydata.org/generated/seaborn.lineplot.html#seaborn.lineplot), you wouldn't even have to define the interval yourself. "By default, the plot aggregates over multiple y values at each value of x and shows an estimate of the central tendency and a confidence interval for that estimate.". But if you want to draw it yourself you could get inspiration from the [source code of this function](https://github.com/mwaskom/seaborn/blob/f5da02c43edcfa210b1ee2817501b72ac0e5f172/seaborn/relational.py#L244). – cglacet Jun 15 '20 at 10:51

1 Answers1

1

The easiest way would be to provide the individual datapoints and then let sns.lineplot compute the confidence interval for you. If you want/need to do it yourself, you can use 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')

enter image description here

Michael Mitter
  • 525
  • 3
  • 9