Interactive Visualizations with Plotly
Plotly produces interactive charts — zoom, pan, hover tooltips, click-to-filter — that are far more effective than static matplotlib figures for exploring complex datasets and communicating findings to stakeholders.
Getting Started with Plotly Express
Plotly Express (px) is the high-level API that produces full interactive charts with a single function call. It mirrors the seaborn API closely, making migration easy.
Common Chart Types with px
<pre><code class="language-python">import plotly.express as px
import pandas as pd
df = pd.read_csv("data.csv")
# Interactive scatter
fig = px.scatter(df, x="age", y="income", color="churn",
hover_data=["name"], opacity=0.6,
title="Age vs Income by Churn")
fig.show()
# Interactive histogram
fig = px.histogram(df, x="income", nbins=40,
color="churn", barmode="overlay",
marginal="box") # adds box plot on the margin
fig.show()</pre>
Correlation Heatmap with Plotly
<pre><code class="language-python">import plotly.express as px
corr = df.corr(numeric_only=True).round(2)
fig = px.imshow(
corr,
text_auto=True,
color_continuous_scale="RdBu_r",
zmin=-1, zmax=1,
title="Feature Correlation Matrix"
)
fig.show()</pre>
Plotly for ML Workflows
Plotly integrates naturally with ML workflows — visualizing model decision boundaries, feature importance bars, learning curves, and confusion matrices interactively helps debug models faster.
Feature Importance Bar Chart
<pre><code class="language-python">from sklearn.ensemble import RandomForestClassifier
import plotly.express as px
import pandas as pd
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train, y_train)
fi = pd.DataFrame({
"feature": X_train.columns,
"importance": model.feature_importances_
}).sort_values("importance", ascending=True)
fig = px.bar(fi, x="importance", y="feature",
orientation="h", title="Feature Importances")
fig.show()</pre>