Menu

Interactive Charts with Plotly Express

Interactive Charts with Plotly Express

Static images cannot be explored, but interactive charts can. Viewers can hover for details, zoom in, and filter what they see. This topic introduces Plotly Express, the simplest way to build interactive charts in Python.

a. Introduction to Plotly Express

Plotly Express is a high-level interface to the Plotly library. It lets you create a full interactive chart with one line of code. It works directly with Pandas DataFrames.

Install it with pip install plotly. Then import it with the short name px.

import plotly.express as px
df = px.data.gapminder().query("year == 2007")
fig = px.scatter(df, x="gdpPercap", y="lifeExp", color="continent")
fig.show()

The chart opens in your notebook or browser. You can hover over any point to see its values, zoom with the mouse, and click the legend to hide or show groups.

b. Creating Interactive Line and Bar Charts

Plotly Express has a function for each major chart type. They share a similar structure, so once you learn one, the others are easy.

fig = px.line(df, x="month", y="sales", color="region", markers=True)
fig = px.bar(df, x="product", y="units", color="region", barmode="group")

Use color to split the data into groups and barmode to choose between grouped and stacked bars. Update titles and labels with the title and labels options.

fig = px.bar(df, x="product", y="units",
title="Units Sold by Product",
labels={"units": "Units Sold", "product": "Product"})

c. Adding Hover Data, Filters, and Animations

Hover data shows extra details when the user points at a mark. You can choose which columns appear with the hover_name and hover_data options.

fig = px.scatter(df, x="gdpPercap", y="lifeExp", size="pop",
color="continent", hover_name="country", log_x=True)

Animations show how data changes over time. The animation_frame option adds a play button and a slider that moves through values, such as years.

fig = px.scatter(px.data.gapminder(), x="gdpPercap", y="lifeExp",
size="pop", color="continent", animation_frame="year",
hover_name="country", log_x=True, range_y=[25, 90])

Animations are engaging, but use them only when change over time is the main story.

d. Exporting Interactive Charts

You can share a Plotly chart as a standalone HTML file. Anyone can open it in a browser and use it with full interactivity, without needing Python.

fig.write_html("chart.html")

To save a static image for reports or slides, use write_image(). It needs the kaleido package installed.

fig.write_image("chart.png", scale=2)

Choose HTML when you want people to explore, and image when you need a fixed picture for documents.


Data Visualization Tutorial

WR

Wesline Rinisha



Learn via Video Course

Data Visualization Using Python Logo

Data Visualization Using Python

19 hrs



Get in Touch For Details