Show Sidebar Hide Sidebar

Subplots in Pandas

How to create a chart with subplots, or small multiples, with Pandas in Python.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Version Check

Plotly's Python package is updated frequently, run pip install plotly --upgrade to upgrade your version.

In [1]:
import plotly
plotly.__version__
Out[1]:
'2.0.7'

Imports

In [3]:
import plotly.plotly as py
import plotly.tools as tls

import cufflinks as cf
print cf.__version__
0.8.2
In [4]:
df=cf.datagen.lines(4,mode='abc')
df[['c','d']]=df[['c','d']]*100

df.iplot(subplots=True, filename='pandas/cufflinks-subplots')
Out[4]:
In [5]:
df.iplot(subplots=True, shape=(4, 1), filename='pandas/cufflinks-subplot rows')
Out[5]:

Combining multiple traces into a single subplot, or mixing and matching chart types, isn't as easy with cufflinks. Subplots are entirely customizable with Plotly's native Python syntax:

In [7]:
fig = tls.make_subplots(rows=2, cols=1, shared_xaxes=True)

for col in ['a', 'b']:
    fig.append_trace({'x': df.index, 'y': df[col], 'type': 'scatter', 'name': col}, 1, 1)
for col in ['c', 'd']:
    fig.append_trace({'x': df.index, 'y': df[col], 'type': 'bar', 'name': col}, 2, 1)
    
py.iplot(fig, filename='pandas/mixed-type subplots')
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x1,y2 ]

Out[7]:

This secondary subplot decouples the hover text from the charts in the top pane and the charts in the bottom pane. You can always customize your hover text, so that all four values are always present:

In [8]:
hover_text = df.apply(lambda r: '<br>'.join(['{}: {}'.format(c, r[c]) 
                                            for c in df.columns]), axis=1)

fig = tls.make_subplots(rows=2, cols=1, shared_xaxes=True)

for col in ['a', 'b']:
    fig.append_trace({'x': df.index, 'y': df[col], 'type': 'scatter', 
                      'name': col, 'text': hover_text}, 1, 1)

for col in ['c', 'd']:
    fig.append_trace({'x': df.index, 'y': df[col], 'type': 'bar', 
                      'name': col, 'text': hover_text}, 2, 1)
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x1,y2 ]

In [9]:
import plotly.plotly as py

py.iplot(fig, filename='pandas/mixed-type subplots with custom hover text')
Out[9]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.