← Back to list

A Quick Start Guide to Plotly Express

The Go-To Tool for Data Scientists & Data Analyst

Rohit in Level Up Coding · 2024-10-01 02:16 · 52 claps · 6.6 min read paywalled
#plotly-express #python #data-visualization #data-science #exploratory-data-analysis
Open on Medium ↗
Wiki topics: FT · Fine-tuning & Adaptation ML · Machine Learning VIS · Visual & Graphic Design 🌐 · Web Development 🔬 · Science · General 📰 · Journalism & News

A Quick Start Guide to Plotly Express

The Go-To Tool for Data Scientists & Data Analyst

by author

by author

As a data scientist or analyst, you have likely used Matplotlib for visualizing data, but if you are looking for a more interactive, flexible, and user friendly tool, Plotly Express is a game changer. Whether you are analyzing data, presenting insights, or creating dashboards. Plotly Express gives you a simpler way to build interactive visualizations without the hassle of extensive coding.

Today, I’ll walk you through the advantages of Plotly Express over Matplotlib, with practical code examples tailored for a data scientist workflow.

-> Why Plotly Express for Data Scientists?

Here’s why Plotly Express is ideal for data science:

  1. Fast Prototyping: You can create high-quality plots in just a few lines of code, allowing you to focus more on analysis and less on the nitty-gritty of plot design.
  2. Interactivity: Built-in interactivity is great for exploratory data analysis (EDA) and communicating insights with non-technical stakeholders.
  3. Web Compatibility: Perfect for embedding visualizations in web apps or sharing reports via dashboards.

-> Installation

First, ensure you have Plotly installed:

pip install plotly

Example: Exploring Sales Data

Let’s say you're working with sales data across various regions and you want to analyze the trends visually.

Code:

import plotly.express as px

# Data
regions = ['North', 'South', 'East', 'West']
sales = [250, 130, 300, 190]

# Plot
fig = px.bar(x=regions, y=sales, title="Sales by Region", labels={'x': 'Region', 'y': 'Sales'})
fig.show()

by author

by author

This simple code snippet produces an interactive bar chart that you can zoom, pan, and hover over for additional details.

Breaking Down Plotly Express Parameters

In the px.bar() function:

  • x: Specifies data for the x-axis (regions in this case).
  • y: Specifies the sales data on the y-axis.
  • title: Adds a title to the plot, making it easy to interpret.
  • labels: Allows you to customize axis labels, so you can make your visualizations clearer for your audience.

-> Customizing Axis and Titles

Updating axis labels and titles is crucial for making your plot more understandable to both technical and non-technical audiences. Here’s how to do that:

fig = px.bar(x=regions, y=sales, title="Regional Sales Comparison",
             labels={'x': 'Region', 'y': 'Total Sales'})
fig.show()

by author

by author

You can quickly adjust the axes and titles based on the context of your analysis.

-> Example, use-case: Sales Data by Product Category

As a data scientist/ analyst, visualizing multiple dimensions of data is often essential for gaining insights. In this example, we will demonstrate how to visualize sales data by product category across different regions.

Data Preparation:

We have sales data categorized by region and product type as follows:

import pandas as pd

# Define the data
regions = ['North', 'North', 'South', 'South', 'East', 'East', 'West', 'West']
products = ['Electronics', 'Furniture', 'Electronics', 'Furniture', 'Electronics', 'Furniture', 'Electronics', 'Furniture']
sales = [200, 50, 100, 30, 250, 50, 150, 40]

# Create a DataFrame
data = {
    'Region': regions,
    'Product': products,
    'Sales': sales
}
df = pd.DataFrame(data)

Creating the Plot:

To distinguish different product types, we can use the color parameter in Plotly Express. Here’s how to create a bar chart to visualize the sales data:

Here’s how you can use the color parameter to distinguish different products:

import plotly.express as px

# Create the bar plot
fig = px.bar(df, x='Region', y='Sales', color='Product', 
             title="Sales by Region and Product",
             labels={'Region': 'Region', 'Sales': 'Sales', 'Product': 'Product Type'})

# Display the plot
fig.show()

by author

by author

By using color to represent each product type, we create a visually distinct chart that makes it easy to compare sales performance across regions.

Setup Interactive Tooltips:

In exploratory data analysis (EDA), interactive tooltips can provide additional context when hovering over data points. By default, all relevant data points are shown when you hover. However, you can control which data is displayed in the tooltip.

For instance, if you want to show only the region and hide the sales figures, you can specify the hover_data parameter:

# Create the bar plot with customized tooltips
fig = px.bar(df, x='Region', y='Sales', color='Product', 
             hover_data={'Region': True, 'Sales': False}, 
             title="Sales by Region and Product")

# Display the plot
fig.show()

In this example, hovering over each bar will display only the region, omitting the sales figures. This allows for greater control over the information presented in the tooltips, enhancing clarity and focus in your visualizations.

Animating Time-Series Data:

Let’s take it up a notch. If you want to visualize how sales evolve over time, you can animate the plot based on months. This is extremely useful for time-series data.

import pandas as pd

data = {
    'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jan', 'Feb', 'Mar', 'Apr', 'May'],
    'Region': ['North', 'North', 'North', 'North', 'North', 'South', 'South', 'South', 'South', 'South'],
    'Sales': [200, 220, 250, 300, 310, 150, 180, 200, 210, 220]
}

df = pd.DataFrame(data)

# Animated plot
fig = px.bar(df, x='Region', y='Sales', color='Region', animation_frame='Month',
             title="Monthly Sales Growth by Region", labels={'x': 'Region', 'y': 'Sales'})
fig.show()

by author

by author

With the animation_frame parameter, you can visualize how data changes month-to-month, giving you insights into seasonal trends.

-> Exploring Data with a 2x2 Plot: Multiple Visualizations in One View

Sometimes, the best way to convey insights from your data is by displaying multiple types of visualizations simultaneously. A 2x2 grid allows you to present different aspects of your data in a compact, easily digestible format. In this example, we will create a 2x2 plot featuring a bar chart, line chart, scatter plot, and box plot, all showcasing the same dataset.

Data Preparation:

Let’s consider a dataset of sales across various regions and product types. Here’s how we can set it up:

import pandas as pd
import plotly.express as px
import plotly.subplots as sp

# Sample Data
data = {
    'Region': ['North', 'North', 'South', 'South', 'East', 'East', 'West', 'West'],
    'Product': ['Electronics', 'Furniture', 'Electronics', 'Furniture', 'Electronics', 'Furniture', 'Electronics', 'Furniture'],
    'Sales': [200, 50, 100, 30, 250, 50, 150, 40],
    'Month': ['Jan', 'Jan', 'Jan', 'Jan', 'Jan', 'Jan', 'Jan', 'Jan']
}
df = pd.DataFrame(data)

Creating the 2x2 Plot:

Now, let’s create the 2x2 plot using Plotly Express. We will combine different types of plots into one figure to provide a comprehensive view of our data:

# Create a 2x2 subplot
fig = sp.make_subplots(rows=2, cols=2, 
                        subplot_titles=("Sales by Region (Bar)", "Sales Over Time (Line)",
                                        "Sales Distribution (Box)", "Sales by Product (Scatter)"))

# Bar Plot
bar_plot = px.bar(df, x='Region', y='Sales', title="Sales by Region", labels={'x': 'Region', 'y': 'Sales'})
for trace in bar_plot.data:
    fig.add_trace(trace, row=1, col=1)

# Line Plot
line_plot = px.line(df, x='Month', y='Sales', color='Region', title="Sales Over Time")
for trace in line_plot.data:
    fig.add_trace(trace, row=1, col=2)

# Box Plot
box_plot = px.box(df, x='Region', y='Sales', title="Sales Distribution by Region")
for trace in box_plot.data:
    fig.add_trace(trace, row=2, col=1)

# Scatter Plot
scatter_plot = px.scatter(df, x='Product', y='Sales', color='Region', title="Sales by Product")
for trace in scatter_plot.data:
    fig.add_trace(trace, row=2, col=2)

# Update layout
fig.update_layout(title_text="Exploring Sales Data: A 2x2 Visualization Grid", height=800)
fig.show()

This code snippet creates a visually appealing 2x2 grid with four distinct plots. Each plot conveys unique insights about the sales data, allowing for easy comparisons and a comprehensive understanding of the data at a glance.

by author

by author

By combining multiple visualizations, you can provide richer insights and engage your audience more effectively. The interactivity of Plotly Express enhances the user experience, making it easy to explore the data further.

-> Why Data Scientists Should Choose Plotly Express Over Matplotlib

  1. Fewer Lines of Code: In Plotly Express, even complex plots can be built in 5-10 lines. With Matplotlib, the same plot would require much more code for customization.
  2. Interactivity: The interactivity of Plotly Express makes it perfect for data scientists who need to explore data visually before running deep analysis. Zooming, panning, and hovering give more context without cluttering the plot.
  3. Easy Customization: While Matplotlib is customizable, it often requires additional code to adjust aspects like axis labels, titles, and legends. In Plotly Express, these can be handled with simple parameters like labels, title, and color.
  4. Web-Friendly: If you’re building dashboards or reports using web frameworks like Dash or Flask, Plotly Express is far more suited for web integration compared to Matplotlib.
  5. Built-in Animations: For time-series or multi-step processes, you can easily create animations to show changes over time without needing extra animation libraries.

Wrapping up

As a data scientist or analyst, Plotly Express provides an easy-to-use, interactive alternative to Matplotlib. Whether you're exploring your data, presenting findings to stakeholders, or building a data dashboard, the ease of customization, interactivity, and simplicity make it a go-to tool for modern data visualizations.

If you haven’t tried it yet, now’s the perfect time to enhance your visualizations with Plotly Express, you might find it’s hard to go back to Matplotlib after seeing the benefits!

Click ➡️ subscribe! If you found this article helpful, don’t forget to hit that Clap button, leave a comment, or follow for more such lovely and interesting content. Your engagement fuels my writing journey! 🌟🧑‍💻🚀


메타데이터
post_id
39efd0bc5312
slug
a-quick-start-guide-to-plotly-express-39efd0bc5312
url
https://levelup.gitconnected.com/a-quick-start-guide-to-plotly-express-39efd0bc5312
canonical_url
https://levelup.gitconnected.com/a-quick-start-guide-to-plotly-express-39efd0bc5312
author_url
https://medium.com/@yash7
status
ok
fetched_at
2026-06-10 09:45:17