Plotly¶
Plotly draws interactive charts: hover for the numbers, drag to zoom, double-click to reset, click a legend item to hide it. If you know Seaborn and Matplotlib, you already know most of it:
- Plotly Express (
px) ≈ Seaborn: one call on a DataFrame. - graph_objects (
go) ≈ Matplotlib's object-oriented style: build the figure trace by trace.
Every figure is data (a list of traces) plus layout (everything else).
The saved outputs in this notebook are static images, so they show on GitHub. Run the notebook to get the interactive charts.
The whole chapter uses one dataset: the Airbnb listings of New York City (2019), already cleaned (the cleaning is done step by step in projects/03-airbnb-nyc). One row per listing, prices in USD per night.
Contents
- The mental model
- Plotly Express
- graph_objects
- Styling
- Subplots
- Hover
- Controls inside the figure
- Maps, 3D, hierarchy, finance
- Saving and exporting
- Gotchas
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
from plotly.subplots import make_subplots
# interactive charts in Jupyter, plus a static PNG copy (needs kaleido) for viewers that can't run JavaScript, such as GitHub
try:
import kaleido # noqa: F401
pio.renderers.default = "plotly_mimetype+png"
pio.renderers["png"].width = 900
except ImportError:
pio.renderers.default = "plotly_mimetype+notebook"
df = pd.read_csv("../data/airbnb/airbnb_cleaned.csv", parse_dates=["last_review"]) # one row per listing, USD per night
print(df.shape)
df.head(3)
(48631, 18)
| id | name | host_id | borough | neighbourhood | latitude | longitude | room_type | price | minimum_nights | number_of_reviews | last_review | reviews_per_month | host_listings | availability_365 | distance_km | distance_band | host_type | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 2539 | Clean & quiet apt home by the park | 2787 | Brooklyn | Kensington | 40.64749 | -73.97237 | Private room | 149 | 1 | 9 | 2018-10-19 | 0.21 | 6 | 365 | 12.337898 | 10+ km | 6+ listings |
| 1 | 2595 | Skylit Midtown Castle | 2845 | Manhattan | Midtown | 40.75362 | -73.98377 | Entire home | 225 | 1 | 45 | 2019-05-21 | 0.38 | 2 | 355 | 0.508366 | < 2 km | 2-5 listings |
| 2 | 3647 | THE VILLAGE OF HARLEM....NEW YORK ! | 4632 | Manhattan | Harlem | 40.80902 | -73.94190 | Private room | 150 | 3 | 0 | NaT | 0.00 | 1 | 365 | 6.757240 | 5-10 km | 1 listing |
⚠️ A Plotly chart carries every row it draws inside the notebook, and 48,000 dots are slow to move. So we chart three small tables, built once here:
sample: 3,000 random listings, for charts of single listings (scatter, box, map)hoods: one row per neighbourhood (listings, median price, median distance to Times Square)wide: listings per month of their last review, one column per borough, from 2018 on.last_reviewis the date of each listing's last review before the data was collected (July 2019), so each listing is counted once: this shows how recently listings were active, not reviews per month.
sample = df.sample(3000, random_state=7)
hoods = (df.groupby(["borough", "neighbourhood"])
.agg(listings=("id", "size"), price=("price", "median"),
distance=("distance_km", "median"), reviews=("number_of_reviews", "sum"))
.reset_index())
monthly = (df.dropna(subset=["last_review"])
.resample("MS", on="last_review").size().rename("listings").reset_index())
wide = (df[df["last_review"] >= "2018-01-01"]
.groupby([pd.Grouper(key="last_review", freq="MS"), "borough"]).size()
.unstack().reset_index())
wide.columns.name = None
ORDERS = {"distance_band": ["< 2 km", "2-5 km", "5-10 km", "10+ km"],
"room_type": ["Entire home", "Private room", "Shared room"],
"host_type": ["1 listing", "2-5 listings", "6+ listings"],
"borough": ["Manhattan", "Brooklyn", "Queens", "Bronx", "Staten Island"]}
print("median price, all:", df["price"].median(), "| sample:", sample["price"].median())
wide.tail(3)
median price, all: 105.0 | sample: 100.0
| last_review | Bronx | Brooklyn | Manhattan | Queens | Staten Island | |
|---|---|---|---|---|---|---|
| 16 | 2019-05-01 | 94.0 | 1524.0 | 1595.0 | 435.0 | 36.0 |
| 17 | 2019-06-01 | 366.0 | 5185.0 | 5193.0 | 1700.0 | 128.0 |
| 18 | 2019-07-01 | 153.0 | 1910.0 | 1729.0 | 848.0 | 79.0 |
hoods.head()
| borough | neighbourhood | listings | price | distance | reviews | |
|---|---|---|---|---|---|---|
| 0 | Bronx | Allerton | 42 | 66.5 | 16.068423 | 1803 |
| 1 | Bronx | Baychester | 7 | 75.0 | 17.498118 | 310 |
| 2 | Bronx | Belmont | 24 | 52.5 | 13.667867 | 296 |
| 3 | Bronx | Bronxdale | 19 | 50.0 | 14.701656 | 458 |
| 4 | Bronx | Castle Hill | 9 | 39.0 | 13.324741 | 118 |
monthly.head()
| last_review | listings | |
|---|---|---|
| 0 | 2011-03-01 | 1 |
| 1 | 2011-04-01 | 1 |
| 2 | 2011-05-01 | 1 |
| 3 | 2011-06-01 | 0 |
| 4 | 2011-07-01 | 0 |
wide.head()
| last_review | Bronx | Brooklyn | Manhattan | Queens | Staten Island | |
|---|---|---|---|---|---|---|
| 0 | 2018-01-01 | 10.0 | 237.0 | 253.0 | 48.0 | NaN |
| 1 | 2018-02-01 | 7.0 | 59.0 | 61.0 | 12.0 | 2.0 |
| 2 | 2018-03-01 | 3.0 | 93.0 | 97.0 | 14.0 | NaN |
| 3 | 2018-04-01 | 2.0 | 135.0 | 147.0 | 27.0 | 1.0 |
| 4 | 2018-05-01 | 7.0 | 176.0 | 190.0 | 27.0 | NaN |
1. The mental model¶
| Matplotlib | Plotly |
|---|---|
Figure |
go.Figure |
Axes |
layout.xaxis / yaxis |
ax.plot() artist |
trace (go.Scatter, go.Bar…) |
ax.set_title() etc. |
fig.update_layout() |
plt.show() |
fig.show() |
med = df.groupby("borough")["price"].median()
med
borough Bronx 65.0 Brooklyn 90.0 Manhattan 149.0 Queens 75.0 Staten Island 75.0 Name: price, dtype: float64
fig = px.bar(x=med.index, y=med.values)
print(fig) # peek at the dict structure: data + layout
Figure({
'data': [{'alignmentgroup': 'True',
'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>',
'legendgroup': '',
'marker': {'color': '#636efa', 'pattern': {'shape': ''}},
'name': '',
'offsetgroup': '',
'orientation': 'v',
'showlegend': False,
'textposition': 'auto',
'type': 'bar',
'x': array(['Bronx', 'Brooklyn', 'Manhattan', 'Queens', 'Staten Island'],
dtype=object),
'xaxis': 'x',
'y': array([ 65., 90., 149., 75., 75.]),
'yaxis': 'y'}],
'layout': {'barmode': 'relative',
'legend': {'tracegroupgap': 0},
'margin': {'t': 60},
'template': '...',
'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}},
'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y'}}}
})
fig.show()
fig = go.Figure()
fig.add_trace(go.Bar(x=med.index, y=med.values, name="median price"))
fig.show()
px.scatter(sample, x="distance_km", y="price", color="room_type", size="number_of_reviews", size_max=25,
hover_data=["neighbourhood"], title="Price vs distance to Times Square")
2.2 Scatter + regression line (≈ sns.regplot)¶
trendline="ols" needs the statsmodels package. One line per colour:
px.scatter(sample.query("price <= 500"), x="distance_km", y="price", color="room_type",
trendline="ols", opacity=0.4)
2.3 Line¶
px likes long data: one row per (month, borough). melt turns wide into long:
wide
| last_review | Bronx | Brooklyn | Manhattan | Queens | Staten Island | |
|---|---|---|---|---|---|---|
| 0 | 2018-01-01 | 10.0 | 237.0 | 253.0 | 48.0 | NaN |
| 1 | 2018-02-01 | 7.0 | 59.0 | 61.0 | 12.0 | 2.0 |
| 2 | 2018-03-01 | 3.0 | 93.0 | 97.0 | 14.0 | NaN |
| 3 | 2018-04-01 | 2.0 | 135.0 | 147.0 | 27.0 | 1.0 |
| 4 | 2018-05-01 | 7.0 | 176.0 | 190.0 | 27.0 | NaN |
| 5 | 2018-06-01 | 5.0 | 173.0 | 169.0 | 32.0 | NaN |
| 6 | 2018-07-01 | 10.0 | 221.0 | 229.0 | 43.0 | 3.0 |
| 7 | 2018-08-01 | 15.0 | 313.0 | 292.0 | 63.0 | 3.0 |
| 8 | 2018-09-01 | 11.0 | 296.0 | 233.0 | 85.0 | 7.0 |
| 9 | 2018-10-01 | 16.0 | 324.0 | 278.0 | 85.0 | 9.0 |
| 10 | 2018-11-01 | 13.0 | 254.0 | 224.0 | 60.0 | 9.0 |
| 11 | 2018-12-01 | 20.0 | 387.0 | 441.0 | 92.0 | 2.0 |
| 12 | 2019-01-01 | 32.0 | 649.0 | 582.0 | 164.0 | 8.0 |
| 13 | 2019-02-01 | 8.0 | 203.0 | 200.0 | 53.0 | 3.0 |
| 14 | 2019-03-01 | 14.0 | 347.0 | 353.0 | 97.0 | 5.0 |
| 15 | 2019-04-01 | 30.0 | 632.0 | 627.0 | 158.0 | 8.0 |
| 16 | 2019-05-01 | 94.0 | 1524.0 | 1595.0 | 435.0 | 36.0 |
| 17 | 2019-06-01 | 366.0 | 5185.0 | 5193.0 | 1700.0 | 128.0 |
| 18 | 2019-07-01 | 153.0 | 1910.0 | 1729.0 | 848.0 | 79.0 |
long = wide.melt(id_vars="last_review", var_name="borough", value_name="listings")
long
| last_review | borough | listings | |
|---|---|---|---|
| 0 | 2018-01-01 | Bronx | 10.0 |
| 1 | 2018-02-01 | Bronx | 7.0 |
| 2 | 2018-03-01 | Bronx | 3.0 |
| 3 | 2018-04-01 | Bronx | 2.0 |
| 4 | 2018-05-01 | Bronx | 7.0 |
| ... | ... | ... | ... |
| 90 | 2019-03-01 | Staten Island | 5.0 |
| 91 | 2019-04-01 | Staten Island | 8.0 |
| 92 | 2019-05-01 | Staten Island | 36.0 |
| 93 | 2019-06-01 | Staten Island | 128.0 |
| 94 | 2019-07-01 | Staten Island | 79.0 |
95 rows × 3 columns
px.line(long, x="last_review", y="listings", color="borough")
2.4 Wide data works too¶
px.line(wide, x="last_review", y=["Manhattan", "Brooklyn", "Queens"])
2.5 Bar: ⚠️ does not aggregate, group first¶
sns.barplot computes a mean for you; px.bar draws what it gets. Give it raw rows and it stacks one thin segment per listing, so each bar becomes the sum of the prices.
agg = df.groupby(["borough", "room_type"], as_index=False)["price"].median()
px.bar(agg, x="borough", y="price", barmode="group", color="room_type",
category_orders=ORDERS)
2.6 Histogram: aggregates for you (≈ sns.histplot)¶
px.histogram(sample, y="price", nbins=50, opacity=0.7, marginal="box" )
Hover the small box plots on top: Plotly prints the quartiles.
# histfunc turns it into an aggregated bar chart (≈ sns.barplot): the mean price per group
px.histogram(sample, x="borough", y="price", histfunc="avg", color="room_type", barmode="group",
category_orders=ORDERS)
2.7 Box / violin / strip¶
Prices are right-skewed, so log_y=True keeps the boxes readable.
px.box(sample, x="borough", y="price", color="room_type", log_y=True,
category_orders=ORDERS)
px.violin(sample, x="room_type", y="price", box=True, color="host_type",
category_orders=ORDERS)
px.strip(sample, x="room_type", y="price", color="host_type", log_y=True, category_orders=ORDERS)
2.8 ECDF & 2D density¶
px.ecdf(sample, x="price", color="room_type", category_orders=ORDERS)
Hover the line at 150: the share of listings that cost $150 or less, per room type.
px.density_heatmap(sample.query("price <= 500"), x="distance_km", y="price", nbinsx=20, nbinsy=20,
marginal_x="histogram")
# longitude/latitude as x/y: a map without a map
px.density_contour(sample, x="longitude", y="latitude", color="room_type", category_orders=ORDERS)
2.9 Heatmap (≈ sns.heatmap)¶
Fix the range to −1…1 for a correlation table, or the colours lie.
cols = ["price", "minimum_nights", "number_of_reviews", "reviews_per_month", "host_listings",
"availability_365", "distance_km"]
px.imshow(df[cols].corr(method="spearman"),
text_auto=".2f", color_continuous_scale="RdBu_r", zmin=-1, zmax=1)
2.10 Pair plot (≈ sns.pairplot)¶
px.scatter_matrix(sample, dimensions=["price", "distance_km", "number_of_reviews", "availability_365"],
opacity=0.4, height=700)
2.11 Pie / donut¶
Unlike px.bar, px.pie sums values per name for you:
hoods.sample()
| borough | neighbourhood | listings | price | distance | reviews | |
|---|---|---|---|---|---|---|
| 148 | Queens | Glendale | 54 | 84.0 | 10.231355 | 1459 |
px.pie(hoods, names="borough", values="listings", hole=0.4)
2.12 Facets (≈ sns.relplot(col=...))¶
fig = px.scatter(sample, x="distance_km", y="price", color="host_type",
facet_col="borough", facet_row="room_type", log_y=True, height=650,
category_orders=ORDERS)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1])) # "borough=Bronx" -> "Bronx"
# wrap many panels: the 12 neighbourhoods with the most listings
top12 = df["neighbourhood"].value_counts().index[:12]
hood_month = (df[df["neighbourhood"].isin(top12) & (df["last_review"] >= "2018-01-01")]
.groupby(["neighbourhood", pd.Grouper(key="last_review", freq="MS")]).size()
.rename("listings").reset_index())
(px.line(hood_month, x="last_review", y="listings", facet_col="neighbourhood", facet_col_wrap=4, height=700)
.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))
.update_yaxes(title=None))
3. graph_objects (≈ Matplotlib OO)¶
One trace ≈ one ax.plot() call. mode: lines · markers · lines+markers · text
fig = go.Figure()
fig.add_trace(go.Scatter(x=wide["last_review"], y=wide["Manhattan"], mode="lines", name="Manhattan",
line=dict(color="royalblue", width=2, dash="dash")))
fig.add_trace(go.Scatter(x=wide["last_review"], y=wide["Brooklyn"], mode="markers", name="Brooklyn",
marker=dict(size=9, symbol="circle-open")))
fig.show()
# mixing trace types: median as bars, mean as dots
stats = df.groupby("borough")["price"].agg(["median", "mean"]).sort_values("median", ascending=False)
fig = go.Figure()
fig.add_trace(go.Bar(x=stats.index, y=stats["median"], name="median"))
fig.add_trace(go.Scatter(x=stats.index, y=stats["mean"], name="mean", mode="lines+markers"))
fig.show()
In every borough the mean sits above the median: a few expensive listings pull it up (the right skew of prices).
# fill between (≈ ax.fill_between): the middle 50% of prices, by month of the last review
band = (df[df["last_review"] >= "2016-01-01"]
.groupby(pd.Grouper(key="last_review", freq="MS"))["price"]
.quantile([0.25, 0.5, 0.75]).unstack())
fig = go.Figure([
go.Scatter(x=band.index, y=band[0.75], line_width=0, showlegend=False),
go.Scatter(x=band.index, y=band[0.25], fill="tonexty", line_width=0, name="Q1-Q3",
fillcolor="rgba(65,105,225,0.2)"),
go.Scatter(x=band.index, y=band[0.5], name="median", line_color="royalblue"),
])
fig.show()
fig = px.scatter(hoods, x="distance", y="price", color="borough")
fig.update_layout(
title=dict(text="Neighbourhoods: the further out, the cheaper", x=0.5), # centered
xaxis_title="Median distance to Times Square (km)", yaxis_title="Median price",
# width=800, height=450, # ≈ figsize
template="presentation", # ['ggplot2', 'seaborn', 'simple_white', 'plotly', 'plotly_white', ...]
legend=dict(orientation="h", y=-0.2),
# font=dict(family="Arial", size=13),
# margin=dict(l=40, r=20, t=60, b=40),
)
fig.update_xaxes(range=[0, 30], showgrid=False) # ≈ set_xlim
fig.update_yaxes(tickprefix="$")
fig.update_traces(marker=dict(size=10, opacity=0.7, line=dict(width=1, color="white")))
fig.show()
# target one trace with selector
fig = px.line(wide, x="last_review", y=ORDERS["borough"])
fig.update_traces(line_width=4, selector=dict(name="Manhattan"))
fig.update_yaxes(type="log") # ≈ set_yscale("log"): Staten Island becomes visible
fig.show()
4.1 Templates¶
for t in ["plotly", "plotly_white", "plotly_dark", "ggplot2", "seaborn", "simple_white"]:
px.scatter(hoods, x="distance", y="price", color="borough",
template=t, title=t, height=300).show()
# global default: pio.templates.default = "simple_white"
4.2 Colours¶
px.scatter(hoods, x="distance", y="price", color="borough",
color_discrete_sequence=px.colors.qualitative.Set2)
px.scatter(hoods, x="distance", y="price", color="listings", log_y=True,
color_continuous_scale="Viridis")
# explicit mapping
px.bar(agg, x="borough", y="price", color="room_type", barmode="group",
color_discrete_map={"Entire home": "#0F766E", "Private room": "#E89B2D", "Shared room": "#D95D4A"})
# explicit mapping
px.bar(agg, x="borough", y="price", color="room_type", barmode="group",
color_discrete_sequence=["#0F766E", "#E89B2D", "#D95D4A"])
4.3 Reference lines, shapes, annotations (≈ axhline, axvspan, annotate)¶
fig = px.line(monthly, x="last_review", y="listings")
fig.add_hline(y=1000, line_dash="dot", annotation_text="1,000 listings")
fig.add_vline(x="2019-01-01", line_color="gray")
fig.add_vrect(x0="2018-11-01", x1="2018-12-31", fillcolor="red", opacity=0.15, line_width=0)
peak = monthly.loc[monthly["listings"].idxmax()]
fig.add_annotation(x=peak["last_review"], y=peak["listings"], text="Peak", showarrow=True, arrowhead=2)
fig.show()
5. Subplots (≈ plt.subplots)¶
fig = make_subplots(rows=1, cols=2, subplot_titles=("Listings by month of last review", "Median price"))
fig.add_trace(go.Scatter(x=monthly["last_review"], y=monthly["listings"], name="listings"), row=1, col=1)
fig.add_trace(go.Bar(x=stats.index, y=stats["median"], name="median"), row=1, col=2)
fig.update_xaxes(title_text="month", row=1, col=1)
fig.update_layout(height=400, showlegend=False)
fig.show()
# 2x2 grid with a panel spanning 2 columns
fig = make_subplots(rows=2, cols=2, specs=[[{"colspan": 2}, None],
[{}, {}]],
subplot_titles=("Wide", "Left", "Right"))
fig.add_trace(go.Scatter(x=wide["last_review"], y=wide["Manhattan"]), row=1, col=1)
fig.add_trace(go.Histogram(x=sample["price"]), row=2, col=1)
fig.add_trace(go.Box(y=sample["price"]), row=2, col=2)
fig.update_layout(height=600, showlegend=False)
fig.show()
6. Hover¶
By default the hover repeats x and y, which the reader can already see. Make it answer the next question: which listing is this?
px.scatter(sample, x="distance_km", y="price", color="room_type", log_y=True,
hover_name="name", # bold title
hover_data={"neighbourhood": True, "room_type": False, "distance_km": ":.1f"},
labels={"distance_km": "Distance to Times Square (km)", "price": "Price (USD)"}) # renames everywhere
# full control; <extra></extra> hides the trace-name box
fig = px.scatter(sample, x="distance_km", y="price", log_y=True,
custom_data=["neighbourhood", "number_of_reviews"])
fig.update_traces(hovertemplate="Distance: %{x:.1f} km<br>Price: $%{y:.0f}"
"<br>%{customdata[0]} · %{customdata[1]} reviews<extra></extra>")
fig.show()
# one tooltip for all series
px.line(wide, x="last_review", y=["Manhattan", "Brooklyn", "Queens"]).update_layout(hovermode="x unified")
7. Controls inside the figure¶
These controls live inside the figure and work in the saved HTML too. One example each; for widgets that drive a whole page, see the Streamlit part.
7.1 Animation¶
One frame per year of the last review: each bubble is a neighbourhood, among the listings last reviewed that year.
yearly = (df.dropna(subset=["last_review"])
.assign(year=lambda t: t["last_review"].dt.year)
.query("year >= 2015")
.groupby(["year", "borough", "neighbourhood"])
.agg(listings=("id", "size"), price=("price", "median"), distance=("distance_km", "median"))
.reset_index())
px.scatter(yearly, x="distance", y="price", size="listings", color="borough",
hover_name="neighbourhood", animation_frame="year", animation_group="neighbourhood",
log_y=True, size_max=55, range_x=[0, 36], range_y=[20, 1000], category_orders=ORDERS)
⚠️ Always fix range_x / range_y, or the axes change with every frame and the bubbles look like they jump when they don't.
7.2 Range slider + selector buttons¶
fig = px.line(monthly, x="last_review", y="listings")
fig.update_xaxes(rangeslider_visible=True, rangeselector=dict(buttons=[
dict(count=3, label="3m", step="month", stepmode="backward"),
dict(count=1, label="1y", step="year", stepmode="backward"),
dict(step="all"),
]))
fig.show()
7.3 Dropdown buttons¶
fig = px.line(monthly, x="last_review", y="listings")
fig.update_layout(updatemenus=[dict(x=0, y=1.15, buttons=[
dict(label="Linear", method="relayout", args=[{"yaxis.type": "linear"}]),
dict(label="Log", method="relayout", args=[{"yaxis.type": "log"}]),
])])
fig.show()
On the log scale the early years (2011–2016) stop hiding at the bottom.
# toggle trace visibility
cols = ["Manhattan", "Brooklyn", "Queens"]
fig = px.line(wide, x="last_review", y=cols)
buttons = [dict(label="All", method="update", args=[{"visible": [True] * 3}])] + [
dict(label=c, method="update", args=[{"visible": [c == k for k in cols]}]) for c in cols]
fig.update_layout(updatemenus=[dict(buttons=buttons, x=0, y=1.15)])
fig.show()
Add type="buttons", direction="right" to the menu dict and the dropdown becomes a row of buttons.
happy = pd.read_csv("../data/world_happiness_2021.csv").rename(columns={
"Country name": "country", "Regional indicator": "region", "Ladder score": "score"})
px.choropleth(happy, locations="country", locationmode="country names", color="score",
hover_name="country", color_continuous_scale="Viridis", range_color=[2, 8],
projection="natural earth")
px.choropleth(happy, locations="country", locationmode="country names", color="score",
hover_name="country", color_continuous_scale="Viridis",
projection="orthographic")
# choropleth projection types:
# equirectangular, mercator, orthographic, natural earth, kavrayskiy7,
# azimuthal equal area, conic equal area, conic conformal, conic equidistant,
# gnomonic, stereographic, mollweide, hammer, transverse mercator, albers usa, winkel tripel
Kosovo is missing: it isn't on Plotly's list of country names. For a map you'll publish, use ISO codes (locationmode="ISO-3").
px.scatter_geo(sample, lat="latitude", lon="longitude", color="borough", fitbounds="locations",
category_orders=ORDERS)
scatter_geo only knows coasts and borders, which is fine for countries but empty for a city. For streets, use a tile map (the tiles come from the internet):
px.scatter_map(sample, lat="latitude", lon="longitude", color="price", range_color=[0, 300],
hover_name="name", zoom=9.5, height=550, map_style="carto-positron")
range_color=[0, 300] caps the colour scale. Without it a handful of $1,000 listings would make every other dot the same pale colour.
8.2 3D¶
fig = px.scatter_3d(sample.query("price <= 500"), x="longitude", y="latitude", z="price",
color="room_type", category_orders=ORDERS)
fig.update_traces(marker_size=2)
# a surface from a 2D count: the "listing mountain" over Manhattan and Brooklyn
counts, xe, ye = np.histogram2d(df["longitude"], df["latitude"], bins=60)
go.Figure(go.Surface(x=(xe[:-1] + xe[1:]) / 2, y=(ye[:-1] + ye[1:]) / 2, z=counts.T,
colorscale="Viridis"))
8.3 Hierarchy¶
Click a slice or a box to zoom into it; click the centre or the top bar to come back.
tree = df.groupby(["borough", "room_type"]).size().rename("listings").reset_index()
px.sunburst(tree, path=["borough", "room_type"], values="listings")
px.treemap(hoods, path=[px.Constant("New York"), "borough"],
values="listings", color="price", color_continuous_scale="RdBu_r",
color_continuous_midpoint=df["price"].median())
8.4 Finance: candlestick¶
A candle summarises a period with four numbers: open (first value), close (last), high, low. Here one candle per month, from the weekly counts of last reviews: resample(...).ohlc() computes all four.
weekly = df.resample("W", on="last_review").size()
ohlc = weekly["2018-01":"2019-06"].resample("MS").ohlc()
go.Figure(go.Candlestick(x=ohlc.index, open=ohlc["open"], high=ohlc["high"],
low=ohlc["low"], close=ohlc["close"])
).update_layout(xaxis_rangeslider_visible=False)
9. Saving and exporting¶
fig.write_html() saves the chart as a web page: whoever opens it gets the full interactive chart in their browser, no Python needed.
from pathlib import Path
Path("output").mkdir(exist_ok=True)
fig = px.scatter(sample, x="distance_km", y="price", color="room_type", log_y=True)
fig.write_html("output/plot.html") # plotly.js inside: works offline
fig.write_html("output/plot_cdn.html", include_plotlyjs="cdn") # plotly.js from the internet
# fig.write_image("plot.png", scale=3) # static: needs kaleido
js = fig.to_json() # for web apps
for f in sorted(Path("output").glob("*.html")):
print(f"{f.name:14} {f.stat().st_size / 1e6:.1f} MB")
plot.html 4.6 MB plot_cdn.html 0.1 MB
A Plotly chart is drawn by a JavaScript library, plotly.js, and include_plotlyjs decides where the browser gets it:
- Default (
True): plotly.js is copied inside the file. Big, but it opens anywhere, even offline: a laptop without internet, a phone, an email attachment. "cdn": the file holds only your data and a line that says "download plotly.js from the internet". Small, but with no internet the reader gets an empty page.
Sending it to someone: the default. Putting it on a website: "cdn".
10. Gotchas¶
- No global state: no
plt.gca(); always holdfig. px.bardoesn't aggregate:groupbyfirst (or usepx.histogramwithhistfunc).- Numbers as strings → categorical axis. Force with
update_xaxes(type="category"). - Every row travels with the chart: aggregate or sample before you plot.
- Big data (>100k points) →
render_mode="webgl"in px, orgo.Scattergl. - Trace order = draw order and legend order.
- Plots blank in Jupyter? Set
pio.renderers.default("notebook","vscode","browser").
# WebGL for large data: all 48,000 listings (rounded to ~100 m so the saved notebook stays light)
px.scatter(x=df["longitude"].round(3), y=df["latitude"].round(3), render_mode="webgl", opacity=0.2)
Summary¶
| Task | Code |
|---|---|
| Import | import plotly.express as px · import plotly.graph_objects as go · from plotly.subplots import make_subplots |
| Scatter / bubble | px.scatter(df, x=, y=, color=, size=, trendline="ols") |
| Line / wide | px.line(long, x=, y=, color=) · px.line(wide, x=, y=[...]) |
| Bar (aggregate first!) | px.bar(table, x=, y=, color=, barmode="group") |
| Histogram | px.histogram(df, x=, nbins=, color=, marginal="box") · histfunc="avg" |
| Box / violin / strip | px.box(..., points="all") · px.violin(..., box=True) · px.strip(...) |
| ECDF / 2D density | px.ecdf · px.density_heatmap · px.density_contour |
| Heatmap / pair plot | px.imshow(corr, text_auto=".2f", zmin=-1, zmax=1) · px.scatter_matrix(df, dimensions=[...]) |
| Pie / donut | px.pie(df, names=, values=, hole=0.4) |
| Facets | facet_col=, facet_row=, facet_col_wrap= · fig.for_each_annotation(...) |
| graph_objects | go.Figure() · fig.add_trace(go.Scatter(mode=...)) · go.Bar · fill="tonexty" |
| Styling | update_layout(...), update_traces(..., selector=), update_xaxes/yaxes(...), template= |
| Colours | color_discrete_sequence= · color_continuous_scale= · color_discrete_map={} |
| Lines & notes | add_hline · add_vline · add_vrect · add_annotation |
| Subplots | make_subplots(rows=, cols=, specs=) · secondary_y=True |
| Hover | hover_name=, hover_data={}, labels={}, custom_data= + hovertemplate, hovermode="x unified" |
| Controls | animation_frame= + range_y= · rangeslider_visible=True · updatemenus=[dict(buttons=[...])] |
| Maps | px.choropleth · px.scatter_geo · px.scatter_map(..., map_style="carto-positron") |
| 3D / hierarchy / finance | px.scatter_3d · go.Surface · px.sunburst / px.treemap(path=[...]) · go.Candlestick |
| Share | fig.write_html("f.html") · include_plotlyjs="cdn" · fig.write_image (needs kaleido) |
| Big data | aggregate or df.sample(3000) · render_mode="webgl" |
Next: More charts: the rarer chart types, one example each.