Plotly 交互式图表实战

2026-06-10 · 阅读 9 分钟 · 机器学习可视化

← 返回首页

Plotly 简介

Plotly 是一个强大的交互式可视化库,支持创建可以在网页上交互的图表。它的优势包括:

安装与设置

pip install plotly

import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np

Plotly Express(快速上手)

散点图

# 使用内置数据集
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,
    title="2007年各国人均GDP与预期寿命"
)
fig.show()

# 保存为 HTML
fig.write_html("scatter_plot.html")

动画图表

# 带动画的散点图
fig = px.scatter(
    df,
    x="gdpPercap",
    y="lifeExp",
    animation_frame="year",
    animation_group="country",
    size="pop",
    color="continent",
    hover_name="country",
    log_x=True,
    size_max=55,
    range_x=[100, 100000],
    range_y=[25, 90],
    title="全球发展变化(1952-2007)"
)
fig.show()

折线图

# 多条折线图
df = px.data.gapminder().query("continent=='Europe'")
fig = px.line(
    df,
    x="year",
    y="lifeExp",
    color="country",
    title="欧洲各国预期寿命变化"
)
fig.show()

柱状图

# 分组柱状图
df = px.data.gapminder().query("year==2007 and continent=='Asia'")
fig = px.bar(
    df,
    x="country",
    y="pop",
    color="lifeExp",
    title="2007年亚洲各国人口",
    hover_data=["gdpPercap"]
)
fig.show()

Plotly Graph Objects(高级定制)

子图

from plotly.subplots import make_subplots

# 创建 2x2 子图
fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("图1", "图2", "图3", "图4")
)

# 添加数据
fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[1, 2, 3], name="折线1"),
    row=1, col=1
)
fig.add_trace(
    go.Bar(x=[1, 2, 3], y=[3, 2, 1], name="柱状图"),
    row=1, col=2
)
fig.add_trace(
    go.Scatter(x=[1, 2, 3], y=[1, 4, 9], name="折线2"),
    row=2, col=1
)
fig.add_trace(
    go.Pie(labels=['A', 'B', 'C'], values=[30, 40, 30]),
    row=2, col=2
)

fig.update_layout(height=600, title_text="子图示例")
fig.show()

3D 图表

# 3D 散点图
np.random.seed(42)
n = 100
df = pd.DataFrame({
    'x': np.random.randn(n),
    'y': np.random.randn(n),
    'z': np.random.randn(n),
    'color': np.random.choice(['A', 'B', 'C'], n)
})

fig = px.scatter_3d(
    df,
    x='x', y='y', z='z',
    color='color',
    title="3D 散点图"
)
fig.show()

# 3D 曲面图
x = np.linspace(-5, 5, 50)
y = np.linspace(-5, 5, 50)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

fig = go.Figure(data=[go.Surface(z=Z, x=x, y=y)])
fig.update_layout(title='3D 曲面图', autosize=False,
                  width=800, height=600)
fig.show()

机器学习可视化案例

决策边界可视化

from sklearn.datasets import make_moons
from sklearn.ensemble import RandomForestClassifier

# 生成数据
X, y = make_moons(n_samples=200, noise=0.2, random_state=42)

# 训练模型
clf = RandomForestClassifier(n_estimators=10, random_state=42)
clf.fit(X, y)

# 创建网格
xx, yy = np.meshgrid(np.linspace(-2, 3, 100), np.linspace(-1.5, 2, 100))
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)

# 可视化
fig = go.Figure()
fig.add_trace(go.Contour(
    x=np.linspace(-2, 3, 100),
    y=np.linspace(-1.5, 2, 100),
    z=Z,
    colorscale='RdBu',
    opacity=0.7
))
fig.add_trace(go.Scatter(
    x=X[y==0, 0], y=X[y==0, 1],
    mode='markers',
    name='类别 0',
    marker=dict(color='red', size=8)
))
fig.add_trace(go.Scatter(
    x=X[y==1, 0], y=X[y==1, 1],
    mode='markers',
    name='类别 1',
    marker=dict(color='blue', size=8)
))
fig.update_layout(title="决策边界可视化")
fig.show()
小贴士: Plotly 图表在 Jupyter Notebook 中会自动显示交互功能。如果在普通 Python 脚本中使用,需要调用 fig.show() 来打开浏览器显示图表。

总结

Plotly 让数据可视化变得更加生动有趣。无论是简单的探索性分析还是复杂的数据应用,Plotly 都能提供强大的支持。