Plotly:如何结合 make_subplots() 和 ff.create_distplot()?
发布日期:2025-05-05 18:21:12 浏览次数:3 分类:精选文章

本文共 2752 字,大约阅读时间需要 9 分钟。

在Plotly中,结合make_subplots()ff.create_distplot()创建分布图和箱线图的复杂图表是一个常见的操作。以下是详细的步骤和代码示例。

步骤1:导入必要的库

首先,我们需要导入Plotly的相关模块:

import plotly.graph_objects as gofrom plotly import toolsfrom plotly import figure_factory as ffimport numpy as np

步骤2:准备数据

我们需要准备数据进行可视化。在这里,我们生成两个随机变量来展示数据分布:

x1 = np.random.randn(100)  # 生成第一个随机变量x2 = np.random.randn(100) + 1  # 生成第二个随机变量

步骤3:创建子图布局

使用tools.make_subplots()创建包含两个子图的布局:

fig = tools.make_subplots(rows=2, cols=1)

步骤4:添加分布图和箱线图

为每组数据创建分布图和箱线图,并将它们添加到相应的子图中。

# 为第一组数据创建分布图和箱线图trace1 = go.Scatter(    x=x1,    y=[0 for _ in x1],    mode='markers',    marker=dict(color='black'),    name='Data 1')trace2 = go.Box(    y=x1,    name='Data 1 Boxplot')# 为第二组数据创建分布图和箱线图trace3 = go.Scatter(    x=x2,    y=[0 for _ in x2],    mode='markers',    marker=dict(color='black'),    showlegend=False)trace4 = go.Box(    y=x2,    name='Data 2 Boxplot',    boxmean=True,    boxmode='overlay')# 将所有轨迹添加到图表中fig.add_traces(    traces=[trace1, trace2, trace3, trace4],    rows=[1, 1, 2, 2],    cols=[1, 1, 1, 1])

步骤5:设置布局

最后,设置图表的布局,包括标题和显示图例:

fig.update_layout(    title='分布和箱线图分析',    showlegend=False)

完整代码示例

以下是完整的代码示例:

import plotly.graph_objects as gofrom plotly import toolsfrom plotly import figure_factory as ffimport numpy as np# 生成数据x1 = np.random.randn(100)x2 = np.random.randn(100) + 1# 创建子图布局fig = tools.make_subplots(rows=2, cols=1)# 添加分布图和箱线图trace1 = go.Scatter(    x=x1,    y=[0 for _ in x1],    mode='markers',    marker=dict(color='black'),    name='Data 1')trace2 = go.Box(    y=x1,    name='Data 1 Boxplot')trace3 = go.Scatter(    x=x2,    y=[0 for _ in x2],    mode='markers',    marker=dict(color='black'),    showlegend=False)trace4 = go.Box(    y=x2,    name='Data 2 Boxplot',    boxmean=True,    boxmode='overlay')fig.add_traces(    traces=[trace1, trace2, trace3, trace4],    rows=[1, 1, 2, 2],    cols=[1, 1, 1, 1])# 设置布局fig.update_layout(    title='分布和箱线图分析',    showlegend=False)# 显示图表fig.show()

人工智能的应用场景

在数据分析和机器学习中,了解数据分布对于选择合适的算法或模型至关重要。例如,假设你正在分析某个股票的历史价格数据,AI模型可以生成假设的正态分布,帮助你验证数据是否符合该分布。

测试用例

为了确保代码在不同环境下正常运行,你可以编写测试用例。以下是一个简单的测试示例:

def test_generate_data():    x1 = np.random.randn(100)    x2 = np.random.randn(100) + 1    assert len(x1) == 100 and len(x2) == 100, "数据长度应为100"    assert x1.mean() != 0 and x2.mean() != 0, "数据均值应不为零"def test_make_subplots():    fig = tools.make_subplots(rows=2, cols=1)    assert len(fig.data) == 4, "应有4条轨迹"    assert fig.layout.title == '分布和箱线图分析', "布局标题不正确"def test_display_chart():    pass  # 由于这是一个交互式库,测试可能需要根据具体环境编写if __name__ == '__main__':    test_generate_data()    test_make_subplots()    try:        test_display_chart()        print("所有测试都通过了")    except AssertionError as e:        print(f"测试失败:{e}")

通过这些步骤和代码示例,你可以轻松地在Plotly中创建分布图和箱线图的复杂图表,满足你的数据分析需求。

上一篇:Plotly:如何绘制累积的“步骤“;直方图?
下一篇:Plotly:如何手动设置 plotly express 散点图中点的颜色?

发表评论

最新留言

做的很好,不错不错
[***.243.131.199]2026年06月19日 21时39分24秒