import plotly.express as px
df = px.data.gapminder().query("country=='Canada'")
fig = px.line(df, x="year", y="lifeExp", title='Life expectancy in Canada')
fig.show()Plotly makes charts for the web, with hover labels, zooming and panning
built in. Its Python library has two levels. Plotly Express
(plotly.express) draws a complete chart from a DataFrame in one call,
and graph objects (plotly.graph_objects) build a figure one trace at a
time. People use it to explore data and to put charts in reports and
dashboards. This page is an online Plotly compiler: the code runs in
your browser, so you can try it without installing anything.
Run the example first, then paste any snippet below into a new cell to try it.
px.data.gapminder() returns the Gapminder dataset as a
pandas DataFrame: life expectancy, population and
GDP per capita for 142 countries, every five years from 1952 to 2007.
The file ships inside the plotly package, so nothing is downloaded.
.query("country=='Canada'") keeps Canada's 12 rows. px.line() puts
year on the x axis and lifeExp on the y axis and sets the title. It
returns a Figure, and fig.show() displays it. Hovering over the line
shows the year and life expectancy at each point.
color splits the bars by the values in another column. Plotly Express
stacks them by default, and barmode="group" puts them side by side.
text_auto=True writes each value on its bar:
import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"quarter": ["Q1", "Q2", "Q3", "Q4"] * 2,
"sales": [120, 135, 150, 170, 90, 110, 105, 130],
"region": ["North"] * 4 + ["South"] * 4,
})
fig = px.bar(df, x="quarter", y="sales", color="region", barmode="group",
text_auto=True, title="Sales by quarter")
fig.show()
This uses the 2007 rows of the same Gapminder data. size scales each
marker by population, color groups the countries by continent,
hover_name puts the country name at the top of each hover label, and
log_x=True puts GDP on a log scale:
import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", size="pop", color="continent",
hover_name="country", log_x=True, size_max=50)
fig.show()
go.Figure() starts an empty figure, and add_trace() adds one series
at a time, each with its own chart type. update_layout() sets the
title, axis titles and other options. Figures from Plotly Express are
the same Figure class, so these methods work on them too:
import plotly.graph_objects as go
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
fig = go.Figure()
fig.add_trace(go.Bar(x=months, y=[20, 14, 23, 25, 22, 30], name="Orders"))
fig.add_trace(go.Scatter(x=months, y=[18, 16, 20, 22, 24, 27], name="Target",
mode="lines+markers"))
fig.update_layout(title="Orders per month", xaxis_title="Month", yaxis_title="Orders")
fig.show()
make_subplots() creates a grid of charts. add_trace() then takes the
row and col to draw in, both counted from 1:
import numpy as np
import plotly.graph_objects as go
from plotly.subplots import make_subplots
rng = np.random.default_rng(seed=0)
x = np.linspace(0, 10, 50)
fig = make_subplots(rows=1, cols=2, subplot_titles=("Signal", "Distribution"))
fig.add_trace(go.Scatter(x=x, y=np.sin(x), name="sin(x)"), row=1, col=1)
fig.add_trace(go.Histogram(x=rng.normal(0, 1, 500), name="Samples"), row=1, col=2)
fig.update_layout(showlegend=False)
fig.show()
fig.write_image(), which saves PNG, SVG or PDF files, needs the
Kaleido package, which does not install in this browser version of
Python. fig.write_html("chart.html") works. It saves a standalone
page of about 4.8 MB, or about 8 KB with include_plotlyjs="cdn",
which loads plotly.js from the internet instead. Files your code saves
appear in the sidebar's Data tab.px.data has more small datasets that ship with the package and load
without a download, such as iris(), tips() and stocks().px.line(df, x="month", y=["sales", "costs"]).