Customise plots created with plotly express: Example Notebook#
import pandas as pd
# Set default template
import plotly.io as pio
pio.templates.default = "plotly_dark"
# Use plot methods on DataFrame directly
pd.options.plotting.backend = "plotly"
# High-level approach
import plotly.express as px
Get life expectancy by country, continent, and year#
all_countries = (
px.data.gapminder()[["country", "continent", "year", "lifeExp"]]
.rename(columns={"lifeExp": "life_expectancy"})
.query("continent in ['Europe', 'Americas']")
)
all_countries
country | continent | year | life_expectancy | |
---|---|---|---|---|
12 | Albania | Europe | 1952 | 55.230 |
13 | Albania | Europe | 1957 | 59.280 |
14 | Albania | Europe | 1962 | 64.820 |
15 | Albania | Europe | 1967 | 66.220 |
16 | Albania | Europe | 1972 | 67.690 |
... | ... | ... | ... | ... |
1639 | Venezuela | Americas | 1987 | 70.190 |
1640 | Venezuela | Americas | 1992 | 71.150 |
1641 | Venezuela | Americas | 1997 | 72.146 |
1642 | Venezuela | Americas | 2002 | 72.766 |
1643 | Venezuela | Americas | 2007 | 73.747 |
660 rows × 4 columns
Starting point#
px.line(
all_countries,
x="year",
y="life_expectancy",
color="country",
)
Prettier axis label#
px.line(
all_countries,
x="year",
y="life_expectancy",
labels={"life_expectancy": "Life expectancy"},
color="country",
)
Removing some Spaghettis with facet columns#
px.line(
all_countries,
x="year",
y="life_expectancy",
labels={"life_expectancy": "Life expectancy"},
color="country",
facet_col="continent",
)
Changing overall appearance#
fig = px.line(
all_countries,
x="year",
y="life_expectancy",
labels={"life_expectancy": "Life expectancy"},
color="country",
facet_col="continent",
template="presentation",
)
fig.update_layout(showlegend=False)
fig.for_each_annotation(lambda a: a.update(text=a.text.split("=")[-1]))