Control the color in stacked area chart

logo of a chart:StackedArea

Once you understand how to create a stacked area chart and which baseline option to choose, it’s highly recommended to custom the colors of your chart. This post explains how to customize colors.

Libraries & Data

Let's start by loading a few libraries and create a simple dataset:

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

df = pd.DataFrame({
   'x': range(1,6),
   'y1': [10,4,6,5,3],
   'y2': [12,2,7,10,1],
   'y3': [8,18,5,7,6]
})
df.head()
x y1 y2 y3
0 1 10 12 8
1 2 4 2 18
2 3 6 7 5
3 4 5 10 7
4 5 3 1 6

Basic color customization

The easiest way to customize the colors of your chart is to pass to the colors argument a list of colors:

fig, ax = plt.subplots(figsize=(10,10), dpi=300)

ax.stackplot(
   df['x'],
   df['y1'],
   df['y2'],
   df['y3'],
   colors = ['#00496FFF', '#0F85A0FF', '#EDD746FF']
)

plt.show()

Linewidth style

The edgecolor argument sets the color of the area borders, while linewidth determines how thick those borders are.

fig, ax = plt.subplots(figsize=(10,10), dpi=300)

ax.stackplot(
   df['x'],
   df['y1'],
   df['y2'],
   df['y3'],
   edgecolor = 'black',
   linewidth = 3,
   colors = ['#00496FFF', '#0F85A0FF', '#EDD746FF']
)

plt.show()

Opacity

We can easily change the opacity of the chart thanks to the alpha argument. Possible values range from 0 (completely transparent) to 1 (completely opaque), and the default one is 1:

fig, ax = plt.subplots(figsize=(10,10), dpi=300)

ax.stackplot(
   df['x'],
   df['y1'],
   df['y2'],
   df['y3'],
   edgecolor = 'black',
   linewidth = 3,
   alpha = 0.6,
   colors = ['#00496FFF', '#0F85A0FF', '#EDD746FF']
)

plt.show()

Pattern inside the areas

fig, ax = plt.subplots(figsize=(10,10), dpi=300)

ax.stackplot(
   df['x'],
   df['y1'],
   df['y2'],
   df['y3'],
   edgecolor = 'black',
   linewidth = 3,
   colors = ['#00496FFF', '#0F85A0FF', '#EDD746FF'],
   hatch=['*', '.', '+']
)

plt.show()

More colors with PyPalettes

Thanks to the pypalettes library, it's super easy to use a large number of palette in your seaborn/matplotlib charts. You can find your dream palette in the color palette finder, and use the get_hex() function with the name of the palette you want. Here is an example with the Acadia palette:

from pypalettes import get_hex

colors = get_hex('Acadia')

fig, ax = plt.subplots(figsize=(10,10), dpi=300)

ax.stackplot(
   df['x'],
   df['y1'],
   df['y2'],
   df['y3'],
   edgecolor = 'black',
   linewidth = 2,
   colors = colors
)

plt.show()

Going further

You might be interested in:

Timeseries

Contact & Edit


👋 This document is a work by Yan Holtz. You can contribute on github, send me a feedback on twitter or subscribe to the newsletter to know when new examples are published! 🔥

This page is just a jupyter notebook, you can edit it here. Please help me making this website better 🙏!