python - 如何在 plotly dash 中将垂直线添加到直方图?

标签 python matplotlib plotly plotly-dash

我有一个在回调时触发的 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}

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

最佳答案

您的代码片段不是很容易重现,而是建立在这个 go.Histogram 的基础上例如,您可以只包括:

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

并得到:

enter image description here

请注意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()

关于python - 如何在 plotly dash 中将垂直线添加到直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68370730/

相关文章:

python - 赋值内置函数

python - KMeans是否在sklearn中自动归一化特征

python - 如何在 Python 中更改或查看 gtk.ListStore 标志

python - 如何在 python 数据框中绘制一系列值的特定颜色?

python - 使用插值和 alpha 将 imshow 保存为 pdf 时出现 Matplotlib 问题

python - 是否可以在没有轴的情况下向绘图添加另一个值?

python - setuptools如何在python setup.py test命令上安装测试依赖

python - 限制 matplotlib 热图中的列

r - 将变量作为参数传递给 plot_ly 函数

javascript - 如何以可绘图格式输出 PHP 结果