You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在Plotly中实现单Y轴多X轴的类Pair Plot图表?

Plotly相关问题解答

一、Plotly是否支持绘制Pair Plot?

当然支持。Plotly Express中的px.scatter_matrix()就是专门生成Pair Plot(散点矩阵图)的工具,它会自动展示数据集中所有数值型变量两两之间的散点关系,对角线位置还可配置为直方图或密度图,用来呈现单变量分布。

示例代码:

import plotly.express as px
df = px.data.iris()
fig = px.scatter_matrix(
    df,
    dimensions=["sepal_length", "sepal_width", "petal_length", "petal_width"],
    color="species"
)
fig.show()

如果需要高度定制化的Pair Plot,也可以用Plotly Graph Objects手动组合子图,但Express的方法足以覆盖大部分常规需求。

二、Plotly能否生成单Y轴对应多X轴的图表?

完全可以,无需使用生成全变量组合的scatter_matrix()。你可以通过手动创建子图布局,将同一个Y变量与不同X变量的图表(散点图、折线图等)排列成一行或一列,实现和Seaborn pairplot指定y_vars参数一致的效果。

示例代码(以鸢尾花数据集为例,固定sepal_length为Y轴,匹配三个不同X变量):

import plotly.graph_objects as go
from plotly.subplots import make_subplots
import plotly.express as px

df = px.data.iris()
# 创建1行3列的子图布局
fig = make_subplots(
    rows=1, cols=3,
    subplot_titles=(
        "sepal_width vs sepal_length",
        "petal_length vs sepal_length",
        "petal_width vs sepal_length"
    )
)

# 批量添加子图(也可手动逐个添加)
x_vars = ["sepal_width", "petal_length", "petal_width"]
color_map = {"setosa":"red", "versicolor":"green", "virginica":"blue"}
for idx, x_col in enumerate(x_vars, 1):
    fig.add_trace(
        go.Scatter(
            x=df[x_col],
            y=df["sepal_length"],
            mode="markers",
            marker_color=df["species"].map(color_map)
        ),
        row=1, col=idx
    )

# 统一设置Y轴标题
for col in range(1,4):
    fig.update_yaxes(title_text="sepal_length", row=1, col=col)

# 调整整体布局
fig.update_layout(height=400, width=1000, title_text="单Y轴对应多X轴图表")
fig.show()

你还可以根据需求替换图表类型,比如换成箱线图、折线图等,或通过循环进一步简化重复代码。

内容的提问来源于stack exchange,提问作者Josh Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:01:10