Plotly Express in Python

Plotly Express is a terse, consistent, high-level API for creating figures.


New to Plotly?

Plotly is a free and open-source graphing library for Python. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Overview

The plotly.express module (usually imported as px) contains functions that can create entire figures at once, and is referred to as Plotly Express or PX. Plotly Express is a built-in part of the plotly library, and is the recommended starting point for creating most common figures. Every Plotly Express function uses graph objects internally and returns a plotly.graph_objects.Figure instance. Throughout the plotly documentation, you will find the Plotly Express way of building figures at the top of any applicable page, followed by a section on how to use graph objects to build similar figures. Any figure created in a single function call with Plotly Express could be created using graph objects alone, but with between 5 and 100 times more code.

Plotly Express provides more than 30 functions for creating different types of figures. The API for these functions was carefully designed to be as consistent and easy to learn as possible, making it easy to switch from a scatter plot to a bar chart to a histogram to a sunburst chart throughout a data exploration session. Scroll down for a gallery of Plotly Express plots, each made in a single function call.

Here is a talk from the SciPy 2021 conference that gives a good introduction to Plotly Express and Dash:

Plotly Express currently includes the following functions:

High-Level Features

The Plotly Express API in general offers the following features:

Plotly Express in Dash

Dash is the best way to build analytical apps in Python using Plotly figures. To run the app below, run pip install dash, click "Download" to get the code and run python app.py.

Get started with the official Dash docs and learn how to effortlessly style & deploy apps like this with Dash Enterprise.

Out[2]:

The following set of figures is just a sampling of what can be done with Plotly Express.

Scatter, Line, Area and Bar Charts

Read more about scatter plots and discrete color.

In [3]:
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species")
fig.show()
22.533.544.54.555.566.577.58
speciessetosaversicolorvirginicasepal_widthsepal_length
In [4]:
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin",
           marginal_x="box", trendline="ols", template="simple_white")
fig.show()
22.533.544.545678
speciessetosaversicolorvirginicasepal_widthsepal_length

Read more about error bars.

In [5]:
import plotly.express as px
df = px.data.iris()
df["e"] = df["sepal_width"]/100
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", error_x="e", error_y="e")
fig.show()
22.533.544.54.555.566.577.58
speciessetosaversicolorvirginicasepal_widthsepal_length

Read more about bar charts.

In [6]:
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group")
fig.show()
FemaleMale0500100015002000
smokerNoYessextotal_bill
In [7]:
import plotly.express as px
df = px.data.medals_long()

fig = px.bar(df, x="medal", y="count", color="nation",
             pattern_shape="nation", pattern_shape_sequence=[".", "x", "+"])
fig.show()
goldsilverbronze051015202530354045
nationSouth KoreaChinaCanadamedalcount

Read more about facet plots.

In [8]:
import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x="sex", y="total_bill", color="smoker", barmode="group", facet_row="time", facet_col="day",
       category_orders={"day": ["Thur", "Fri", "Sat", "Sun"], "time": ["Lunch", "Dinner"]})
fig.show()
MaleFemale0200400600800MaleFemaleMaleFemaleMaleFemale0200400600800
smokerNoYessexsexsexsextotal_billtotal_billday=Thurday=Friday=Satday=Suntime=Dinnertime=Lunch
In [9]:
import plotly.express as px
df = px.data.iris()
fig = px.scatter_matrix(df, dimensions=["sepal_width", "sepal_length", "petal_width", "petal_length"], color="species")
fig.show()
2344567801223424645678012246
speciessetosaversicolorvirginicasepal_widthsepal_lengthpetal_widthpetal_lengthsepal_widthsepal_lengthpetal_widthpetal_length

Read more about parallel coordinates and parallel categories, as well as continuous color.

In [10]:
import plotly.express as px
df = px.data.iris()
fig = px.parallel_coordinates(df, color="species_id", labels={"species_id": "Species",
                  "sepal_width": "Sepal Width", "sepal_length": "Sepal Length",
                  "petal_width": "Petal Width", "petal_length": "Petal Length", },
                    color_continuous_scale=px.colors.diverging.Tealrose, color_continuous_midpoint=2)
fig.show()
11.522.53Species4.555.566.577.5Sepal Length7.94.322.533.54Sepal Width4.42123456Petal Length6.910.511.522.5Petal Width2.50.111.21.41.61.822.22.42.62.83Species31
In [11]:
import plotly.express as px
df = px.data.tips()
fig = px.parallel_categories(df, color="size", color_continuous_scale=px.colors.sequential.Inferno)
fig.show()
FemalesexMaleNosmokerYesSundaySatThurFriDinnertimeLunch2size34165
123456size

Read more about hover labels.

In [12]:
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df.query("year==2007"), x="gdpPercap", y="lifeExp", size="pop", color="continent",
           hover_name="country", log_x=True, size_max=60)
fig.show()
2345678910002345678910k234564050607080
continentAsiaEuropeAfricaAmericasOceaniagdpPercaplifeExp

Read more about animations.

In [13]:
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_frame="year", animation_group="country",
           size="pop", color="continent", hover_name="country", facet_col="continent",
           log_x=True, size_max=45, range_x=[100,100000], range_y=[25,90])
fig.show()
1002510002510k25100k304050607080901002510002510k25100k1002510002510k25100k1002510002510k25100k1002510002510k25100k
continentAsiaEuropeAfricaAmericasOceaniayear=1952195219571962196719721977198219871992199720022007gdpPercapgdpPercapgdpPercapgdpPercapgdpPercaplifeExpcontinent=Asiacontinent=Europecontinent=Africacontinent=Americascontinent=Oceania

Read more about line charts.

In [14]:
import plotly.express as px
df = px.data.gapminder()
fig = px.line(df, x="year", y="lifeExp", color="continent", line_group="country", hover_name="country",
        line_shape="spline", render_mode="svg")
fig.show()
19601970198019902000304050607080
continentAsiaEuropeAfricaAmericasOceaniayearlifeExp

Read more about area charts.

In [15]:
import plotly.express as px
df = px.data.gapminder()
fig = px.area(df, x="year", y="pop", color="continent", line_group="country")
fig.show()
1960197019801990200001B2B3B4B5B6B
continentAsiaEuropeAfricaAmericasOceaniayearpop

Read more about timeline/Gantt charts.

In [16]:
import plotly.express as px
import pandas as pd

df = pd.DataFrame([
    dict(Task="Job A", Start='2009-01-01', Finish='2009-02-28', Resource="Alex"),
    dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15', Resource="Alex"),
    dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30', Resource="Max")
])

fig = px.timeline(df, x_start="Start", x_end="Finish", y="Resource", color="Resource")
fig.show()
Jan 2009Feb 2009Mar 2009Apr 2009May 2009Jun 2009MaxAlex
ResourceAlexMaxResource

Read more about funnel charts.

In [17]:
import plotly.express as px
data = dict(
    number=[39, 27.4, 20.6, 11, 2],
    stage=["Website visit", "Downloads", "Potential customers", "Requested price", "Invoice sent"])
fig = px.funnel(data, x='number', y='stage')
fig.show()
3927.420.6112Invoice sentRequested pricePotential customersDownloadsWebsite visit
stage

Part to Whole Charts

Read more about pie charts.

In [18]:
import plotly.express as px
df = px.data.gapminder().query("year == 2007").query("continent == 'Europe'")
df.loc[df['pop'] < 2.e6, 'country'] = 'Other countries' # Represent only large countries
fig = px.pie(df, values='pop', names='country', title='Population of European continent')
fig.show()
14.1%12.1%10.4%10.4%9.92%6.9%6.57%3.8%2.83%1.83%1.82%1.77%1.75%1.73%1.7%1.54%1.4%1.29%1.25%0.933%0.929%0.894%0.79%0.777%0.767%0.701%0.614%0.343%0.168%
GermanyTurkeyFranceUnited KingdomItalySpainPolandRomaniaNetherlandsGreecePortugalBelgiumCzech RepublicSerbiaHungarySwedenAustriaSwitzerlandBulgariaDenmarkSlovak RepublicFinlandNorwayBosnia and HerzegovinaCroatiaIrelandAlbaniaSloveniaOther countriesPopulation of European continent

Read more about sunburst charts.

In [19]:
import plotly.express as px

df = px.data.gapminder().query("year == 2007")
fig = px.sunburst(df, path=['continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'])
fig.show()
AsiaAfricaAmericasEuropeOceaniaChinaIndiaIndonesiaPakistanBangladeshJapanPhilippinesVietnamIranThailandKorea, Rep.MyanmarAfghanistanNepalSaudi ArabiaIraqMalaysiaKorea, Dem. Rep.TaiwanYemen, Rep.Sri LankaSyriaCambodiaHong Kong, ChinaIsraelJordanSingaporeWest Bank and GazaLebanonOmanMongoliaKuwaitBahrainNigeriaEgyptEthiopiaCongo, Dem. Rep.South AfricaSudanTanzaniaKenyaMoroccoAlgeriaUgandaGhanaMozambiqueMadagascarCote d'IvoireCameroonBurkina FasoMalawiNigerAngolaZimbabweSenegalMaliZambiaTunisiaChadGuineaSomaliaRwandaBurundiBeninSierra LeoneLibyaTogoEritreaCentral African RepublicCongo, Rep.MauritaniaLiberiaNamibiaLesothoGambiaBotswanaGuinea-BissauGabonMauritiusSwazilandReunionComorosEquatorial GuineaDjiboutiSao Tome and PrincipeUnited StatesBrazilMexicoColombiaArgentinaCanadaPeruVenezuelaChileEcuadorGuatemalaCubaDominican RepublicBoliviaHaitiHondurasEl SalvadorParaguayNicaraguaCosta RicaPuerto RicoUruguayPanamaJamaicaTrinidad and TobagoGermanyTurkeyFranceUnited KingdomItalySpainPolandRomaniaNetherlandsGreecePortugalBelgiumCzech RepublicSerbiaHungarySwedenAustriaSwitzerlandBulgariaDenmarkSlovak RepublicFinlandNorwayBosnia and HerzegovinaCroatiaIrelandAlbaniaSloveniaMontenegroIcelandAustraliaNew Zealand
404550556065707580lifeExp

Read more about treemaps.

In [20]:
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.treemap(df, path=[px.Constant('world'), 'continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'])
fig.show()
worldAsiaAfricaAmericasEuropeOceaniaChinaIndiaIndonesiaPakistanBangladeshJapanPhilippinesVietnamIranThailandKorea, Rep.MyanmarAfghanistanNepalSaudi ArabiaIraqMalaysiaKorea, Dem. Rep.TaiwanYemen, Rep.Sri LankaSyriaCambodiaHong Kong, ChinaIsraelJordanSingaporeWest Bank and GazaLebanonOmanMongoliaKuwaitBahrainNigeriaEgyptEthiopiaCongo, Dem. Rep.South AfricaSudanTanzaniaKenyaMoroccoAlgeriaUgandaGhanaMozambiqueMadagascarCote d'IvoireCameroonBurkina FasoMalawiNigerAngolaZimbabweSenegalMaliZambiaTunisiaChadGuineaSomaliaRwandaBurundiBeninSierra LeoneLibyaTogoEritreaCentral African RepublicCongo, Rep.MauritaniaLiberiaNamibiaLesothoGambiaBotswanaGuinea-BissauGabonMauritiusSwazilandReunionComorosEquatorial GuineaDjibouti United StatesBrazilMexicoColombiaArgentinaCanadaPeruVenezuelaChileEcuadorGuatemalaCubaDominican RepublicBoliviaHaitiHondurasEl SalvadorParaguayNicaraguaCosta RicaPuerto RicoUruguayPanamaJamaicaTrinidad and TobagoGermanyTurkeyFranceUnited KingdomItalySpainPolandRomaniaNetherlandsGreecePortugalBelgiumCzech RepublicSerbiaHungarySwedenAustriaSwitzerlandBulgariaDenmarkSlovak RepublicFinlandNorwayBosnia and HerzegovinaCroatiaIrelandAlbaniaSloveniaMontenegroIceland
404550556065707580lifeExp

Read more about icicle charts.

In [21]:
import plotly.express as px
import numpy as np
df = px.data.gapminder().query("year == 2007")
fig = px.icicle(df, path=[px.Constant('world'), 'continent', 'country'], values='pop',
                  color='lifeExp', hover_data=['iso_alpha'])
fig.show()
worldAsiaAfricaAmericasEuropeOceaniaChinaIndiaIndonesiaPakistanBangladeshJapanPhilippinesVietnamIranThailandKorea, Rep.MyanmarAfghanistanNepalSaudi ArabiaIraqMalaysiaKorea, Dem. Rep.TaiwanYemen, Rep.Sri LankaSyriaCambodiaHong Kong, ChinaIsraelJordanSingaporeWest Bank and GazaLebanonOmanMongoliaKuwaitBahrainNigeriaEgyptEthiopiaCongo, Dem. Rep.South AfricaSudanTanzaniaKenyaMoroccoAlgeriaUgandaGhanaMozambiqueMadagascarCote d'IvoireCameroonBurkina FasoMalawiNigerAngolaZimbabweSenegalMaliZambiaTunisiaChadGuineaSomaliaRwandaBurundiBeninSierra LeoneLibyaTogoEritreaCentral African RepublicCongo, Rep.MauritaniaLiberiaNamibiaLesothoGambiaBotswanaGuinea-BissauGabonMauritiusSwazilandReunionComorosEquatorial GuineaDjiboutiSao Tome and PrincipeUnited StatesBrazilMexicoColombiaArgentinaCanadaPeruVenezuelaChileEcuadorGuatemalaCubaDominican RepublicBoliviaHaitiHondurasEl SalvadorParaguayNicaraguaCosta RicaPuerto RicoUruguayPanamaJamaicaTrinidad and TobagoGermanyTurkeyFranceUnited KingdomItalySpainPolandRomaniaNetherlandsGreecePortugalBelgiumCzech RepublicSerbiaHungarySwedenAustriaSwitzerlandBulgariaDenmarkSlovak RepublicFinlandNorwayBosnia and HerzegovinaCroatiaIrelandAlbaniaSloveniaMontenegroIcelandAustraliaNew Zealand
404550556065707580lifeExp

Distributions

Read more about histograms.

In [22]:
import plotly.express as px
df = px.data.tips()
fig = px.histogram(df, x="total_bill", y="tip", color="sex", marginal="rug", hover_data=df.columns)
fig.show()
1020304050020406080
sexFemaleMaletotal_billsum of tip

Read more about box plots.

In [23]:
import plotly.express as px
df = px.data.tips()
fig = px.box(df, x="day", y="total_bill", color="smoker", notched=True)
fig.show()
SunSatThurFri1020304050
smokerNoYesdaytotal_bill

Read more about violin plots.

In [24]:
import plotly.express as px
df = px.data.tips()
fig = px.violin(df, y="tip", x="smoker", color="sex", box=True, points="all", hover_data=df.columns)
fig.show()
NoYes0246810
sexFemaleMalesmokertip
In [25]:
import plotly.express as px
df = px.data.tips()
fig = px.ecdf(df, x="total_bill", color="sex")
fig.show()
510152025303540455000.20.40.60.81
sexFemaleMaletotal_billprobability

Read more about strip charts.

In [26]:
import plotly.express as px
df = px.data.tips()
fig = px.strip(df, x="total_bill", y="time", orientation="h", color="smoker")
fig.show()
1020304050DinnerLunch
smokerNoYestotal_billtime
In [27]:
import plotly.express as px
df = px.data.iris()
fig = px.density_contour(df, x="sepal_width", y="sepal_length")
fig.show()
1.522.533.544.5544.555.566.577.58
sepal_widthsepal_length
In [28]:
import plotly.express as px
df = px.data.iris()
fig = px.density_heatmap(df, x="sepal_width", y="sepal_length", marginal_x="rug", marginal_y="histogram")
fig.show()
22.533.544.544.555.566.577.58
024681012141618countsepal_widthsepal_length

Images and Heatmaps

Read more about heatmaps and images.

In [29]:
import plotly.express as px
data=[[1, 25, 30, 50, 1], [20, 1, 60, 80, 30], [30, 60, 1, 5, 20]]
fig = px.imshow(data,
                labels=dict(x="Day of Week", y="Time of Day", color="Productivity"),
                x=['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
                y=['Morning', 'Afternoon', 'Evening']
               )
fig.update_xaxes(side="top")
fig.show()
MondayTuesdayWednesdayThursdayFridayEveningAfternoonMorning
1020304050607080ProductivityDay of WeekTime of Day
In [30]:
import plotly.express as px
from skimage import io
img = io.imread('https://upload.wikimedia.org/wikipedia/commons/thumb/0/00/Crab_Nebula.jpg/240px-Crab_Nebula.jpg')
fig = px.imshow(img)
fig.show()
050100150200200150100500

Tile Maps

Read more about tile maps and point on tile maps.

In [31]:
import plotly.express as px
df = px.data.carshare()
fig = px.scatter_map(df, lat="centroid_lat", lon="centroid_lon", color="peak_hour", size="car_hours",
                  color_continuous_scale=px.colors.cyclical.IceFire, size_max=15, zoom=10,
                  map_style="carto-positron")
fig.show()
© CARTO, © OpenStreetMap contributors
05101520peak_hour

Read more about tile map GeoJSON choropleths.

In [32]:
import plotly.express as px

df = px.data.election()
geojson = px.data.election_geojson()

fig = px.choropleth_map(df, geojson=geojson, color="Bergeron",
                           locations="district", featureidkey="properties.district",
                           center={"lat": 45.5517, "lon": -73.7073},
                           map_style="carto-positron", zoom=9)
fig.show()
100020003000400050006000Bergeron

Outline Maps

Read more about outline symbol maps.

In [33]:
import plotly.express as px
df = px.data.gapminder()
fig = px.scatter_geo(df, locations="iso_alpha", color="continent", hover_name="country", size="pop",
               animation_frame="year", projection="natural earth")
fig.show()
continentAsiaEuropeAfricaAmericasOceaniayear=1952195219571962196719721977198219871992199720022007

Read more about choropleth maps.

In [34]:
import plotly.express as px
df = px.data.gapminder()
fig = px.choropleth(df, locations="iso_alpha", color="lifeExp", hover_name="country", animation_frame="year", range_color=[20,80])
fig.show()
year=195219521957196219671972197719821987199219972002200720304050607080lifeExp

Polar Coordinates

Read more about polar plots.

In [35]:
import plotly.express as px
df = px.data.wind()
fig = px.scatter_polar(df, r="frequency", theta="direction", color="strength", symbol="strength",
            color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()
NNNENEENEEESESESSESSSWSWWSWWWNWNWNNW00.511.522.5
strength0-11-22-33-44-44-55-66+

Read more about radar charts.

In [36]:
import plotly.express as px
df = px.data.wind()
fig = px.line_polar(df, r="frequency", theta="direction", color="strength", line_close=True,
            color_discrete_sequence=px.colors.sequential.Plasma_r)
fig.show()
NNNENEENEEESESESSESSSWSWWSWWWNWNWNNW00.511.522.5
strength0-11-22-33-44-44-55-66+

Read more about polar bar charts.

In [37]:
import plotly.express as px
df = px.data.wind()
fig = px.bar_polar(df, r="frequency", theta="direction", color="strength", template="plotly_dark",
            color_discrete_sequence= px.colors.sequential.Plasma_r)
fig.show()
NNNENEENEEESESESSESSSWSWWSWWWNWNWNNW0246810
strength0-11-22-33-44-44-55-66+

3D Coordinates

Read more about 3D scatter plots.

In [38]:
import plotly.express as px
df = px.data.election()
fig = px.scatter_3d(df, x="Joly", y="Coderre", z="Bergeron", color="winner", size="total", hover_name="district",
                  symbol="result", color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"})
fig.show()
winner, resultJoly, pluralityJoly, majorityCoderre, pluralityCoderre, majorityBergeron, pluralityBergeron, majority

Ternary Coordinates

Read more about ternary charts.

In [39]:
import plotly.express as px
df = px.data.election()
fig = px.scatter_ternary(df, a="Joly", b="Coderre", c="Bergeron", color="winner", size="total", hover_name="district",
                   size_max=15, color_discrete_map = {"Joly": "blue", "Bergeron": "green", "Coderre":"red"} )
fig.show()
00.20.40.60.8110.80.60.40.2010.80.60.40.20
winnerJolyCoderreBergeronJolyCoderreBergeron

What About Dash?

Dash is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.

Learn about how to install Dash at https://dash.plot.ly/installation.

Everywhere in this page that you see fig.show(), you can display the same figure in a Dash application by passing it to the figure argument of the Graph component from the built-in dash_core_components package like this:

import plotly.graph_objects as go # or plotly.express as px
fig = go.Figure() # or any Plotly Express function e.g. px.bar(...)
# fig.add_trace( ... )
# fig.update_layout( ... )

from dash import Dash, dcc, html

app = Dash()
app.layout = html.Div([
    dcc.Graph(figure=fig)
])

app.run_server(debug=True, use_reloader=False)  # Turn off reloader if inside Jupyter