Download this Jupyter notebook:
Click here to download the.ipynbfile
(Or use the “Download” button in the top right of the page if available.)
plotly.jsplotly.express (px): one function call per chart, works directly on data framesplotly.graph_objects (go): build a figure trace by trace for full controlconda install plotly or pip install plotlycountry, continent, year, lifeExp, pop, gdpPercappx.data.gapminder(), which also includes ISO country codes for maps(1704, 8)
| country | continent | year | lifeExp | pop | gdpPercap | iso_alpha | iso_num | |
|---|---|---|---|---|---|---|---|---|
| 0 | Afghanistan | Asia | 1952 | 28.801 | 8425333 | 779.445314 | AFG | 4 |
| 1 | Afghanistan | Asia | 1957 | 30.332 | 9240934 | 820.853030 | AFG | 4 |
| 2 | Afghanistan | Asia | 1962 | 31.997 | 10267083 | 853.100710 | AFG | 4 |
| 3 | Afghanistan | Asia | 1967 | 34.020 | 11537966 | 836.197138 | AFG | 4 |
| 4 | Afghanistan | Asia | 1972 | 36.088 | 13079460 | 739.981106 | AFG | 4 |
color and sizesize_max sets the diameter, in pixels, of the largest bubblecolor draws one line per countryimport plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
log_x=True,
title="Wealthier countries live longer (2007)",
labels={"gdpPercap": "GDP per capita (US$, log scale)",
"lifeExp": "Life expectancy (years)",
"continent": "Continent"})
fig.show()hover_name sets the bold title; hover_data adds, hides, or formats columns:, adds thousands separators, :.1f keeps one decimal"red") or hex codes ("#E69F00")import plotly.express as px
df = px.data.gapminder().query("year == 2007")
palette = {"Africa": "#E69F00", "Americas": "#56B4E9", "Asia": "#009E73",
"Europe": "#CC79A7", "Oceania": "#0072B2"}
fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
color_discrete_map=palette, log_x=True)
fig.show()fig.update_layout() changes layout settings after the figure is created; template applies a complete built-in themefacet_col creates one column per continent; the last line shortens the panel titlesanimation_frame sets the frames; animation_group tells Plotly which marker is the same country across framesplotly.graph_objects, the low-level interface that Plotly Express is built onimport plotly.express as px
import plotly.graph_objects as go
df = px.data.gapminder()
us = df[df["country"] == "United States"]
cn = df[df["country"] == "China"]
world = df.groupby("year", as_index=False)["lifeExp"].mean()
dip = cn.loc[cn["year"] == 1962, "lifeExp"].iloc[0]
fig = go.Figure()
fig.add_trace(go.Scatter(x=us["year"], y=us["lifeExp"],
mode="lines+markers", name="United States"))
fig.add_trace(go.Scatter(x=cn["year"], y=cn["lifeExp"],
mode="lines+markers", name="China"))
fig.add_trace(go.Scatter(x=world["year"], y=world["lifeExp"],
mode="lines", name="World average",
line=dict(dash="dash", color="gray")))
fig.add_annotation(x=1962, y=dip, text="Dip after the 1959-61 famine",
showarrow=True, arrowhead=2, ax=40, ay=40)
fig.update_layout(xaxis_title="Year", yaxis_title="Life expectancy (years)")
fig.show()update that sets which traces are visiblecolor creates one trace per continent, each button shows a single traceimport plotly.express as px
df = px.data.gapminder().query("year == 2007")
continents = sorted(df["continent"].unique())
fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent",
hover_name="country", log_x=True,
category_orders={"continent": continents})
n = len(continents)
buttons = [dict(label="All", method="update",
args=[{"visible": [True] * n}])]
for i, name in enumerate(continents):
buttons.append(dict(label=name, method="update",
args=[{"visible": [j == i for j in range(n)]}]))
fig.update_layout(updatemenus=[dict(buttons=buttons, x=0, y=1.15,
xanchor="left")])
fig.show()include_plotlyjs="cdn" keeps the file small by loading plotly.js from the web; use True for a fully offline fileSaved gapminder_2007.html
| Task | Python (plotly.express) |
R (plotly) |
|---|---|---|
| Scatter | px.scatter(df, x=, y=) |
plot_ly(df, x = ~, y = ~, type = "scatter") |
| Line | px.line() |
mode = "lines" |
| Bar | px.bar() |
type = "bar" |
| Histogram | px.histogram() |
type = "histogram" |
| Box | px.box() |
type = "box" |
| Color, size | color=, size= |
color = ~, size = ~ |
| Hover text | hover_name=, hover_data= |
text = ~, hovertemplate = |
| Log axis | log_x=True |
layout(xaxis = list(type = "log")) |
| Layout | fig.update_layout() |
layout() |
| Facets | facet_col= |
subplot() |
| Animation | animation_frame= |
frame = ~ |
| Map | px.choropleth() |
type = "choropleth" |
| Add a layer | fig.add_trace() |
add_trace() |
| Save | fig.write_html() |
htmlwidgets::saveWidget() |