如何用Plotly绘制水平图比较1个自变量与多个因变量?
用Plotly实现Seaborn pairplot单自变量对多因变量的水平图效果
Plotly的splom确实没有Seaborn那样的x_vars/y_vars参数,但可以通过两种方式实现相同效果:
方法1:用Plotly splom手动指定维度
通过自定义dimensions列表筛选变量组合,只保留自变量与每个因变量的散点图:
import plotly.figure_factory as ff import seaborn as sns # 加载示例数据 iris = sns.load_dataset("iris") # 指定自变量和因变量 x_col = "sepal_length" y_cols = ["sepal_width", "petal_length", "petal_width"] # 构造splom的维度列表:先加自变量,再依次添加因变量 dimensions = [{"label": x_col, "values": iris[x_col]}] for col in y_cols: dimensions.append({"label": col, "values": iris[col]}) # 生成splom图,关闭对角线和上半部分子图 fig = ff.create_scatterplotmatrix( iris, dimensions=dimensions, diagonal_visible=False, showupperhalf=False, title="单自变量对多因变量的splom图" ) fig.show()
方法2:用make_subplots逐个绘制子图(贴合Seaborn效果)
如果想要完全复刻Seaborn pairplot的垂直排列样式,用make_subplots逐个添加散点图更灵活:
import plotly.express as px import plotly.subplots as sp import seaborn as sns # 加载示例数据 iris = sns.load_dataset("iris") # 指定自变量和因变量 x_col = "sepal_length" y_cols = ["sepal_width", "petal_length", "petal_width"] # 创建垂直排列的子图布局 fig = sp.make_subplots(rows=len(y_cols), cols=1, subplot_titles=y_cols) # 循环添加每个因变量的散点图 for idx, y_col in enumerate(y_cols, 1): trace = px.scatter(iris, x=x_col, y=y_col).data[0] fig.add_trace(trace, row=idx, col=1) # 仅底部子图显示x轴标签 if idx == len(y_cols): fig.update_xaxes(title_text=x_col, row=idx, col=1) # 设置每个子图的y轴标签 fig.update_yaxes(title_text=y_col, row=idx, col=1) # 调整布局避免标题重叠 fig.update_layout(height=250*len(y_cols), title_text="单自变量对多因变量的散点子图", showlegend=False) fig.show()
内容的提问来源于stack exchange,提问作者david serero
相关产品推荐
相关产品推荐

