By Fatskills Exam Guides Team — the exam nerds behind 28,500+ quizzes and 2.1M practice questions across 500+ global exams.
(Python for Data Science – Production-Ready, Exam-Ready, Hands-On)
Plotly Express (PX) is a high-level Python library for creating interactive, publication-quality visualizations with minimal code. It’s built on top of Plotly.js (a JavaScript library) but abstracts away the complexity—think of it like seaborn for interactivity.
seaborn
matplotlib
You’re a data scientist at an e-commerce company. Your boss asks for a real-time dashboard showing sales trends, customer segments, and product performance. You have 2 hours to prototype something that: - Lets users filter by region, product category, and time range.- Updates dynamically when new data arrives.- Works on mobile and desktop.
Without PX: You’d spend hours tweaking matplotlib or seaborn, then manually add interactivity with JavaScript.With PX: You write 10 lines of Python, deploy it to Dash/Streamlit, and hand over a fully interactive prototype.
px.scatter()
Figure
fig = px.scatter(...)
fig.update_layout()
hover_data
facet_col="region"
animation_frame="year"
config={"displayModeBar": False}
plotly
plotly_white
ggplot2
px.defaults.template = "plotly_white"
px.scatter_3d()
pip install plotly-express pandas
import pandas as pd import plotly.express as px # Load data (or generate fake data) df = pd.read_csv("data.csv") # Replace with your dataset # OR generate fake data: df = pd.DataFrame({ "date": pd.date_range("2023-01-01", "2023-12-31", freq="D"), "sales": np.random.randint(100, 1000, size=365), "region": np.random.choice(["North", "South", "East", "West"], size=365), "product": np.random.choice(["A", "B", "C"], size=365), "profit": np.random.uniform(10, 50, size=365) }) df["month"] = df["date"].dt.month_name()
fig = px.line( df, x="date", y="sales", color="region", # Split by region title="Daily Sales by Region", labels={"sales": "Revenue (USD)", "date": "Date"}, hover_data=["profit"], # Show profit on hover template="plotly_white" ) fig.show()
Expected Output:- Interactive line chart with 4 colored lines (one per region).- Hover shows date, sales, region, and profit.- Zoom/pan controls in the top-right.
date
sales
region
profit
fig.update_layout( updatemenus=[ dict( type="dropdown", buttons=list([ dict(label="All Regions", method="update", args=[{"visible": [True, True, True, True]}]), dict(label="North", method="update", args=[{"visible": [True, False, False, False]}]), dict(label="South", method="update", args=[{"visible": [False, True, False, False]}]), ]), direction="down", pad={"r": 10, "t": 10}, showactive=True, x=0.1, xanchor="left", y=1.1, yanchor="top" ), ] ) fig.show()
Why This Matters:- Stakeholders can self-serve insights without writing code.- Reduces clutter by hiding irrelevant data.
fig = px.bar( df, x="month", y="sales", color="product", facet_col="region", # Split into subplots by region title="Monthly Sales by Product and Region", height=600, category_orders={"month": ["January", "February", ..., "December"]} # Fix month order ) fig.update_layout(showlegend=False) # Reduce clutter fig.show()
Production Tip:- Facets are great for comparisons, but avoid >3 columns (use dropdowns instead).
# Save as HTML (self-contained) fig.write_html("sales_dashboard.html") # Save as JSON (for dynamic updates) fig.write_json("sales_dashboard.json") # Save as PNG (static) fig.write_image("sales_dashboard.png", scale=2) # High-res
When to Use Each:- HTML: Best for dashboards (e.g., Streamlit/Dash).- JSON: Use if you need to update the plot dynamically (e.g., with new data).- PNG: For reports/emails where interactivity isn’t needed.
df.sample(10000)
df.groupby("month").sum()
px.scatter(..., animation_frame=None)
px.scatter(..., render_mode="webgl")
custom_data
fig.update_layout(modebar_remove=["zoom", "pan"])
fig.add_layout_image(dict(source="logo.png", x=0, y=1, sizex=0.2, sizey=0.2))
dcc.Graph(figure=fig)
st.plotly_chart(fig)
fig.write_image()
fig = pio.read_json("file.json")
plots.py
def sales_trend(df): ...
python def sales_trend(df: pd.DataFrame, region: str = None) -> go.Figure: """Generate an interactive sales trend plot. Args: df: DataFrame with columns ['date', 'sales', 'region']. region: Filter by region (None = all regions). """
category_orders
category_orders={"month": ["Jan", "Feb", ...]}
hover_data=["profit", "region"]
fig.update_layout(autosize=True, height=500)
include_plotlyjs
fig.write_html("file.html", include_plotlyjs="cdn")
"Which Plotly Express function creates a scatter plot?"
px.plot()
px.line()
Interactivity Features:
"How do you add a dropdown filter to a Plotly Express figure?"
fig.update_layout(updatemenus=[...])
px.scatter(..., dropdown=True)
Performance:
"Your Plotly Express scatter plot with 500K points is slow. What’s the fix?"
render_mode="webgl"
fig.update_layout(width=2000)
Export Formats:
fig
mpld3
plt.scatter()
sns.FacetGrid
Task:Create an interactive 3D scatter plot showing the relationship between sales, profit, and region in the fake dataset from Step 2. Add: - A color scale for profit.- Hover data showing product and date.- A title: "Sales vs. Profit by Region (3D)".
product
Solution:
fig = px.scatter_3d( df, x="sales", y="profit", z="region", color="profit", color_continuous_scale="Viridis", title="Sales vs. Profit by Region (3D)", hover_data=["product", "date"], height=600 ) fig.show()
Why It Works:- scatter_3d creates a 3D plot (unlike scatter, which is 2D).- color="profit" maps profit to the color scale.- hover_data adds extra fields to tooltips.
scatter_3d
scatter
color="profit"
pip install plotly-express
px.scatter(df, x="col1", y="col2", color="col3")
px.line(df, x="date", y="sales", color="region")
px.bar(df, x="month", y="sales", facet_col="region")
px.histogram(df, x="sales", nbins=20)
px.box(df, x="region", y="profit")
px.scatter_3d(df, x="sales", y="profit", z="region")
px.scatter(df, facet_col="region", facet_col_wrap=2)
fig.update_layout(updatemenus=[dict(type="dropdown", buttons=[...])])
hover_data={"profit": ":.2f"}
fig.write_html("plot.html", include_plotlyjs="cdn")
fig.write_image("plot.png", scale=2)
Join 4M+ learners. Unlock unlimited quizzes, wrong-answer tracking, flashcards + reminders, study guides, and 1-on-1 challenges.