raven
raven

Reputation: 527

How to graph a seaborn lineplot more specifically

Given a mass DataFrame df:

year        count
1980        -23
1980        -4
1981        10
1982        0
1982        4
...
2007        27
2008        0
2008        0
2009        -7
2009        5

with values sorted by year first, and then count. (the values displayed are arbitrarily changed)

I'd like to visualize how the count distributes differently as year increases, which can be most effectively displayed by a percentile plot. However, since my data are given in a DataFrame, I thought a more feasible (and quite frankly, simpler) way would be to use seaborn.lineplot:

import matplotlib.pyplot as plt
import seaborn as sns

fig, ax = plt.subplots(figsize=[16,12])

plt.axhline(y=0, color='black', linestyle='dotted')
sns.lineplot(x="year", y="count", ax=ax, data=df, color='red')

which returns:

enter image description here

This graph somewhat serves a purpose, although I would like the display to have more variabilities than just a single percentile gradient. (A good example would be a figure below with 10 percentile gradients, copied from this link: Using percentiles of a timeseries to set colour gradient in Python's matplotlib)

enter image description here

I'd like to know if there is a way to achieve such detailed graphing using seaborn.lineplot, and if not, if there is a way to do so from a pandas DataFrame data.

Upvotes: 1

Views: 1820

Answers (1)

StupidWolf
StupidWolf

Reputation: 46968

Once you have generated the first confidence interval or just the line, you can use matplotlib, as shown in this post to create multiple confidence interval.

The other option is to plot on the same figure using sns.lineplot, though I think seaborn is not meant for this. Using dataset flights as an example, first we plot the median or mean line:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

flights = sns.load_dataset("flights")
fig,ax = plt.subplots(1,1)

sns.lineplot(data=flights, x="year", y="passengers",ax=ax,ci=None,color="black")

Then we set up a color palette and keep adding the bands without the lines (setting linestyle = ''):

cm = sns.color_palette("Blues",9)

for ix,ci in enumerate(range(10,90,10)):
    sns.lineplot(data=flights, x="year", y="passengers",
                 ci = ci,
                 ax=ax,linestyle='',
                 hue = ci,palette={ci:cm[ix]})

Gives something like this:

enter image description here

Upvotes: 1

Related Questions