【问题标题】:How to add vertical lines to a histogram in plotly dash?如何在短划线中向直方图添加垂直线?
【发布时间】:2021-09-22 23:58:51
【问题描述】:

我有一个在回调时触发的graph 组件。这是我从回调函数绘制直方图的代码。

xtup = np.random.lognormal(90, 3, size=1000)
xtup = list(map('{:.0f}'.format,xtup[0]))
xarr = np.asarray(xtup).astype(np.float)

data = [go.Histogram(
                     x = xarr,
                     nbinsx=50,
                     marker=dict(color="rgb(105,105,105)",
                                 opacity=0.5
                                ),

       )]

layout = {
            "xaxis": {'title': 'Values',
                      'tickformat': '${:,.0f}'
                      #'range': [xarr.min(), xarr.max()]
                     },
            "title": "Distribution",
            "width": 650,
            "height": 400,
            "autosize": True
}

return{'data':data, 'layout':layout}

我想在分布的平均值处添加一条垂直虚线。

【问题讨论】:

    标签: python matplotlib plotly plotly-dash


    【解决方案1】:

    您的代码 sn-p 不是很容易重现,但在此 go.Histogram 示例的基础上,您可以只包括:

    fig.add_vline(x=np.median(df.total_bill), line_dash = 'dash', line_color = 'firebrick')
    

    得到:

    请注意,add_vline 需要最新的 plotly 版本才能正常运行。

    完整代码:

    import plotly.express as px
    import numpy as np
    df = px.data.tips()
    fig = px.histogram(df, x="total_bill")
    fig.add_vline(x=np.median(df.total_bill), line_dash = 'dash', line_color = 'firebrick')
    fig.show()
    

    【讨论】: