【问题标题】:Plotly: How to show other values than counts for marginal histogram?Plotly:如何显示除边际直方图计数之外的其他值?
【发布时间】:2021-02-03 15:21:43
【问题描述】:

我正在尝试在原始图上方创建一个链接的边缘图,具有相同的 x 轴但具有不同的 y 轴。

我看到在plotly.express 包中有 4 个选项,您可以在其中在散点图上创建边缘_x 图,但它们都基于与 x 和 y 相同的列。

就我而言,我的 x 轴上有一个日期,y 轴上有某物的比率,我正在尝试生成该比率所基于的样本的直方图边际分布图(位于df 中的示例列)。

我在不减少任何重要细节的情况下简化了我的尝试:

import pandas as pd
import plotly.express as px

df = pd.DataFrame(
    {
        "date": [pd.Timestamp("20200102"), pd.Timestamp("20200103")],
        "rate": [0.88, 0.96],
        "samples": [130, 1200])
    }
)

fig = px.scatter(df, x='date', y='rate', marginal_x='histogram')
fig.show()

我基于的文档:https://plotly.com/python/marginal-plots/

我想要的结果: Example:

不同之处在于我使用聚合的 df,所以我的计数只有 1,而不是样本数量。

有什么想法吗?

谢谢!

【问题讨论】:

    标签: python pandas plotly plotly-python plotly.graph-objects


    【解决方案1】:

    我理解你的说法

    [...] 和我的 y 轴上某物的速率

    ... 表示您希望在直方图上显示一个 计数的值。

    px.scatter() 中的

    marginal_x='histogram' 似乎默认显示计数,这意味着没有直接的方法来显示单个观察值的值。但是,如果您愿意将fig = make_subplots()go.Scatter()go.Bar() 结合使用,那么您可以轻松构建:

    情节

    完整代码:

    import pandas as pd
    import numpy as np
    from datetime import datetime, timedelta
    from plotly.subplots import make_subplots
    import plotly.graph_objects as go
    
    fig = make_subplots(rows=2, cols=1,
                        row_heights=[0.2, 0.8],
                        vertical_spacing = 0.02,
                        shared_yaxes=False,
                        shared_xaxes=True)
    
    df = pd.DataFrame(
        {
            "date": [pd.Timestamp("20200102"), pd.Timestamp("20200103")],
            "rate": [0.88, 0.96],
            "samples": [130, 1200]
        }
    )
    
    fig.add_trace(go.Bar(x=df['date'], y=df['rate'], name = 'rate'), row = 1, col = 1)
    
    fig.update_layout(bargap=0,
                      bargroupgap = 0,
                     )
    
    fig.add_trace(go.Scatter(x=df['date'], y=df['samples'], name = 'samples'), row = 2, col = 1)
    fig.update_traces(marker_color = 'rgba(0,0,250, 0.3)',
                      marker_line_width = 0,
                      selector=dict(type="bar"))
    
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-15
      • 2012-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2020-11-01
      • 2017-01-04
      • 1970-01-01
      相关资源
      最近更新 更多