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!
Plotly's python package is updated frequently. Run pip install plotly --upgrade
to use the latest version.
import plotly
plotly.__version__
'3.4.0rc1'
import plotly.graph_objs as go
import pandas as pd
import numpy as np
import ipywidgets as widgets
The parallel categories trace is a visualization of multi-dimensional categorical data sets. Each variable in the data set is represented by a column of rectangles, where each rectangle corresponds to a discrete value taken on by that variable. The relative heights of the rectangles reflect the relative frequency of occurrence of the corresponding value.
Combinations of category rectangles across dimensions are connected by ribbons, where the height of the ribbon corresponds to the relative frequency of occurrence of the combination of categories in the data set.
In this first example, we visualize the hair color, eye color, and sex of a sample of 8 people. Hovering over a category rectangle displays a tooltip with the number of people with that single trait. Hovering over a ribbon in the diagram displays a tooltip with the number of people with a particular combination of the three traits connected by the ribbon.
The dimension labels can be dragged horizontally to reorder the dimensions and the category rectangles can be dragged vertically to reorder the categories within a dimension.
parcats = go.Parcats(
dimensions=[
{'label': 'Hair',
'values': ['Black', 'Black', 'Black', 'Brown',
'Brown', 'Brown', 'Red', 'Brown']},
{'label': 'Eye',
'values': ['Brown', 'Brown', 'Brown', 'Brown',
'Brown', 'Blue', 'Blue', 'Blue']},
{'label': 'Sex',
'values': ['Female', 'Female', 'Female', 'Male',
'Female', 'Male', 'Male', 'Male']}]
)
go.FigureWidget(data=[parcats], layout={'width': 800})
FigureWidget({ 'data': [{'dimensions': [{'label': 'Hair', 'values': [Black, …
If the frequency of occurrence for each combination of attributes is known in advance, this can be specified using the counts
property
parcats = go.Parcats(
dimensions=[
{'label': 'Hair',
'values': ['Black', 'Brown', 'Brown', 'Brown', 'Red']},
{'label': 'Eye',
'values': ['Brown', 'Brown', 'Brown', 'Blue', 'Blue']},
{'label': 'Sex',
'values': ['Female', 'Male', 'Female', 'Male', 'Male']}],
counts=[6, 10, 40, 23, 7]
)
go.FigureWidget(data=[parcats], layout={'width': 800})
FigureWidget({ 'data': [{'counts': [6, 10, 40, 23, 7], 'dimensions': [{'label': 'Hair', 'val…
The color of the ribbons can be specified with the line.color
property. Similar to other trace types, this property may be set to an array of numbers, which are then mapped to colors according to the the colorscale specified in the line.colorscale
property.
Here is an example of visualizing the survival rate of passengers in the titanic dataset, where the ribbons are colored based on survival outcome.
By setting the hoveron
property to 'color'
and the hoverinfo
property to 'count+probability'
the tooltips now display count and probability information for each color (outcome) per category.
By setting the arrangement
property to 'freeform'
it is now possible to drag categories horizontally to reorder dimensions as well as vertically to reorder categories within the dimension.
titanic_df = pd.read_csv("https://gist.githubusercontent.com/michhar/2dfd2de0d4f8727f873422c5d959fff5/raw/ff414a1bcfcba32481e4d4e8db578e55872a2ca1/titanic.csv", sep='\t')
titanic_df.head()
PassengerId | Survived | Pclass | Name | Sex | Age | SibSp | Parch | Ticket | Fare | Cabin | Embarked | |
---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 0 | 3 | Braund, Mr. Owen Harris | male | 22.0 | 1 | 0 | A/5 21171 | 7.2500 | NaN | S |
1 | 2 | 1 | 1 | Cumings, Mrs. John Bradley (Florence Briggs Th... | female | 38.0 | 1 | 0 | PC 17599 | 71.2833 | C85 | C |
2 | 3 | 1 | 3 | Heikkinen, Miss. Laina | female | 26.0 | 0 | 0 | STON/O2. 3101282 | 7.9250 | NaN | S |
3 | 4 | 1 | 1 | Futrelle, Mrs. Jacques Heath (Lily May Peel) | female | 35.0 | 1 | 0 | 113803 | 53.1000 | C123 | S |
4 | 5 | 0 | 3 | Allen, Mr. William Henry | male | 35.0 | 0 | 0 | 373450 | 8.0500 | NaN | S |
# Create dimensions
class_dim = go.parcats.Dimension(
values=titanic_df.Pclass,
categoryorder='category ascending',
label="Class"
)
gender_dim = go.parcats.Dimension(
values=titanic_df.Sex,
label="Gender"
)
survival_dim = go.parcats.Dimension(
values=titanic_df.Survived,
label="Outcome",
categoryarray=[0, 1],
ticktext=['perished', 'survived'],
)
# Create parcats trace
color = titanic_df.Survived;
colorscale = [[0, 'lightsteelblue'], [1, 'mediumseagreen']];
data = [
go.Parcats(
dimensions=[class_dim, gender_dim, survival_dim],
line={'color': color,
'colorscale': colorscale},
hoveron='color',
hoverinfo='count+probability',
arrangement='freeform'
)
]
layout = go.Layout(title='Titanic Survival',
font={'family': 'Serif', 'size': 18},
width=800)
# Create figure
go.FigureWidget(data, layout=layout)
FigureWidget({ 'data': [{'arrangement': 'freeform', 'dimensions': [{'categoryorder': 'catego…
This example demonstrates how the on_selection
and on_click
callbacks can be used to implement linked brushing between 3 categorical dimensions displayed with a parcats
trace and 2 continuous dimensions displayed with a scatter
trace.
This example also sets the line.shape
property to hspline
to cause the ribbons to curve between categories.
Note: In order for the callback functions to be executed the figure must be a FigureWidget
, and the figure should display itself. In particular the plot
and iplot
functions should not be used.
cars_df = pd.read_csv('https://raw.githubusercontent.com/mtrebi/d3_cars/e90ede77443df72e714863f876e921cfb2977b56/data/imports-85.csv')
cars_df.head()
symboling | normalized-losses | make | fuel-type | aspiration | num-of-doors | body-style | drive-wheels | engine-location | wheel-base | ... | engine-size | fuel-system | bore | stroke | compression-ratio | horsepower | peak-rpm | city-mpg | highway-mpg | price | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 3 | NaN | alfa-romero | gas | std | two | convertible | rwd | front | 88.6 | ... | 130 | mpfi | 3.47 | 2.68 | 9.0 | 111.0 | 5000.0 | 21 | 27 | 13495.0 |
1 | 3 | NaN | alfa-romero | gas | std | two | convertible | rwd | front | 88.6 | ... | 130 | mpfi | 3.47 | 2.68 | 9.0 | 111.0 | 5000.0 | 21 | 27 | 16500.0 |
2 | 1 | NaN | alfa-romero | gas | std | two | hatchback | rwd | front | 94.5 | ... | 152 | mpfi | 2.68 | 3.47 | 9.0 | 154.0 | 5000.0 | 19 | 26 | 16500.0 |
3 | 2 | 164.0 | audi | gas | std | four | sedan | fwd | front | 99.8 | ... | 109 | mpfi | 3.19 | 3.40 | 10.0 | 102.0 | 5500.0 | 24 | 30 | 13950.0 |
4 | 2 | 164.0 | audi | gas | std | four | sedan | 4wd | front | 99.4 | ... | 136 | mpfi | 3.19 | 3.40 | 8.0 | 115.0 | 5500.0 | 18 | 22 | 17450.0 |
5 rows × 26 columns
# Build parcats dimensions
categorical_dimensions = [
'body-style',
'drive-wheels',
'fuel-type'
];
dimensions = [
dict(values=cars_df[label], label=label)
for label in categorical_dimensions
]
# Build figure as FigureWidget
color = np.zeros(len(cars_df), dtype='uint8')
colorscale = [[0, 'gray'], [1, 'firebrick']]
fig = go.FigureWidget(
data=[
go.Scatter(
x=cars_df.horsepower,
y=cars_df['highway-mpg'],
marker={'color': 'gray'},
mode='markers',
selected={'marker': {'color': 'firebrick'}},
unselected={'marker': {'opacity': 0.3}}),
go.Parcats(
domain={'y': [0, 0.4]},
dimensions=dimensions,
line={
'colorscale': colorscale,
'cmin': 0,
'cmax': 1,
'color': color,
'shape': 'hspline'})
],
layout=go.Layout(
height=800,
width=800,
xaxis={'title': 'Horsepower'},
yaxis={'title': 'MPG',
'domain': [0.6, 1]},
dragmode='lasso',
font={'size': 16},
hovermode='closest')
)
# Update color callback
def update_color(trace, points, state):
# Update scatter selection
fig.data[0].selectedpoints = points.point_inds
# Update parcats colors
new_color = np.zeros(len(cars_df), dtype='uint8')
new_color[points.point_inds] = 1
fig.data[1].line.color = new_color
# Register callback on scatter selection...
fig.data[0].on_selection(update_color)
# and parcats click
fig.data[1].on_click(update_color)
# Display figure
fig
FigureWidget({ 'data': [{'marker': {'color': 'gray'}, 'mode': 'markers', 'sele…
This example extends the previous example to support brushing with multiple colors. The radio buttons above may be used to select the active color, and this color will be applied when points are selected in the scatter
trace and when categories or ribbons are clicked in the parcats
trace.
# Build parcats dimensions
categorical_dimensions = [
'body-style',
'drive-wheels',
'fuel-type'
];
dimensions = [
dict(values=cars_df[label], label=label)
for label in categorical_dimensions
]
# Build parcats trace
color = np.zeros(len(cars_df), dtype='uint8')
colorscale = [[0, 'gray'], [0.33, 'gray'],
[0.33, 'firebrick'], [0.66, 'firebrick'],
[0.66, 'blue'], [1.0, 'blue']];
cmin = -0.5
cmax = 2.5
# Build figure as FigureWidget
fig = go.FigureWidget(
data=[
go.Scatter(
x=cars_df.horsepower,
y=cars_df['highway-mpg'],
marker={'color': color,
'cmin': cmin,
'cmax': cmax,
'colorscale': colorscale,
'showscale': True,
'colorbar': {'tickvals': [0, 1, 2],
'ticktext': ['None', 'Red', 'Blue']}
},
mode='markers'),
go.Parcats(
domain={'y': [0, 0.4]},
dimensions=dimensions,
line={
'colorscale': colorscale,
'cmin': cmin,
'cmax': cmax,
'color': color,
'shape': 'hspline'})
],
layout=go.Layout(
height=800,
width=800,
xaxis={'title': 'Horsepower'},
yaxis={'title': 'MPG',
'domain': [0.6, 1]},
dragmode='lasso',
font={'size': 16},
hovermode='closest')
)
# Build color selection widget
color_toggle = widgets.ToggleButtons(
options=['None', 'Red', 'Blue'],
index=1,
description='Brush Color:',
disabled=False,
)
# Update color callback
def update_color(trace, points, state):
# Compute new color array
new_color = np.array(fig.data[0].marker.color)
new_color[points.point_inds] = color_toggle.index
with fig.batch_update():
# Update scatter color
fig.data[0].marker.color = new_color
# Update parcats colors
fig.data[1].line.color = new_color
# Register callback on scatter selection...
fig.data[0].on_selection(update_color)
# and parcats click
fig.data[1].on_click(update_color)
# Display figure
widgets.VBox([color_toggle, fig])
VBox(children=(ToggleButtons(description='Brush Color:', index=1, options=('None', 'Red', 'Blue'), value='Red'…