Streamgraph with Python and Matplotlib


Streamcharts are a bit tricky to build with Python and Matplotlib. This blogpost will guide you through a complete example, starting with a stacked area chart and transforming it into a streamgraph thanks to data interpolation.

Load data

Basic stacked area chart

# library
import numpy as np
import matplotlib.pyplot as plt

# Create data
x=range(1,6)
y1=[1,23,2,18,9]
y2=[22,52,27,13,12]
y3=[22,8,65,12,16]

# Basic stacked area chart.
plt.stackplot(x,y1, y2, y3, labels=['A','B','C'])
[<matplotlib.collections.PolyCollection at 0x12fb5fdf0>,
 <matplotlib.collections.PolyCollection at 0x12fb6d130>,
 <matplotlib.collections.PolyCollection at 0x12fb6d400>]

Change the baseline parameter


# Basic stacked area chart.
plt.stackplot(x,y1, y2, y3, labels=['A','B','C'], baseline='sym')
[<matplotlib.collections.PolyCollection at 0x12fbf5fa0>,
 <matplotlib.collections.PolyCollection at 0x12fa1ef40>,
 <matplotlib.collections.PolyCollection at 0x12fc034f0>]

Let's get smooth with interp1d

from scipy.interpolate import make_interp_spline
tnew = np.linspace(1, 5, num=100, endpoint=True)
f = make_interp_spline(x, y1, k=2)
y1Smooth = f(tnew)

f = make_interp_spline(x, y2, k=2)
y2Smooth = f(tnew)

f = make_interp_spline(x, y3, k=2)
y3Smooth = f(tnew)

plt.stackplot(tnew, y1Smooth, y2Smooth, y3Smooth, labels=['A','B','C'], baseline='zero')
[<matplotlib.collections.PolyCollection at 0x12fd299a0>,
 <matplotlib.collections.PolyCollection at 0x12fd29c40>,
 <matplotlib.collections.PolyCollection at 0x12fd29f10>]
plt.stackplot(tnew, y1Smooth, y2Smooth, y3Smooth, labels=['A','B','C'], baseline='sym')
[<matplotlib.collections.PolyCollection at 0x12fdb86d0>,
 <matplotlib.collections.PolyCollection at 0x12fdb89d0>,
 <matplotlib.collections.PolyCollection at 0x12fdb8ca0>]

Make it pretty

  • Change colors
  • add labels at the right place manually

Line chart

Area chart

Stacked Area

Streamgraph

Contact & Edit

👋 This document is a work by Yan Holtz. Any feedback is highly encouraged. You can fill an issue on Github, drop me a message onTwitter, or send an email pasting yan.holtz.data with gmail.com.

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

Violin

Density

Histogram

Boxplot

Ridgeline

Scatterplot

Heatmap

Correlogram

Bubble

Connected Scatter

2D Density

Barplot

Spider / Radar

Wordcloud

Parallel

Lollipop

Circular Barplot

Treemap

Venn Diagram

Donut

Pie Chart

Dendrogram

Circular Packing

Line chart

Area chart

Stacked Area

Streamgraph

Map

Choropleth

Hexbin

Cartogram

Connection

Bubble

Chord Diagram

Network

Sankey

Arc Diagram

Edge Bundling

Colors

Interactivity

Animation with python

Animation

Cheat sheets

Caveats

3D