Stefan Smirnov
Stefan Smirnov

Reputation: 785

How to fill area under line plot in seaborn

I want to fill the area under a line plot so it looks as the picture below: it should look like it

instead of

enter image description here

built on the following .csv file:

01-01-97    1
01-02-97    2
01-03-97    3
     ...
01-11-17    251
01-12-17    252
01-01-18    253

what should I change in this code to generate the desired graph?

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

# load csv
df=pd.read_csv("test.csv")
# generate graph
g = sns.lineplot(x="Date", y="Data", data=df)

plt.show()

Upvotes: 10

Views: 22998

Answers (3)

Phenyl
Phenyl

Reputation: 583

To fill area under the curve of faceted plots, you can also use Axes.fill_between(), like in the very convenient function posted in this GitHub ticket. Full credit goes to Michael Waskom, I am just copying his work below for convenience.

def fill_under_lines(ax=None, alpha=.2, **kwargs):
    if ax is None:
        ax = plt.gca()
    for line in ax.lines:
        x, y = line.get_xydata().T
        ax.fill_between(x, 0, y, color=line.get_color(), alpha=alpha, **kwargs)

He also gave an alternative solution leveraging Seaborn's object interface in a later answer to the same ticket.

import seaborn.objects as so
so.Plot(data, "xname", "yname").add(so.Line()).add(so.Area(edgewidth=0))

Upvotes: 1

Vishal
Vishal

Reputation: 580

Here's an alternative, using a stacked line chart:

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

# load csv
df = pd.read_csv("test.csv")

# generate graph
plt.stackplot(df["Date"], df["Data"], alpha=0.5) 

plt.show()

Upvotes: 4

VanTan
VanTan

Reputation: 657

plt.fill_between(df.Date.values, df.Data.values)

Upvotes: 15

Related Questions