Plotly:如何在直方图中显示正态分布和核密度估计?

Plotly: How to show both a normal distribution and a kernel density estimation in a histogram?

对于 plotly figure 工厂分布图,默认分布为 kde (kernel density estimation):

您可以通过设置 curve = 'normal' 覆盖默认值以获得:

但是如何在同一张图中同时显示 kde 和正态曲线?分配像 curve_type = ['kde', 'normal'] 这样的列表是行不通的。

完整代码:

import plotly.figure_factory as ff
import plotly.graph_objects as go
import plotly.express as px
import numpy as np
np.random.seed(2)

x = np.random.randn(1000)
hist_data = [x]
group_labels = ['distplot'] # name of the dataset

mean = np.mean(x)
stdev_pluss = np.std(x)
stdev_minus = np.std(x)*-1

fig = ff.create_distplot(hist_data, group_labels, curve_type='kde')
fig.update_layout(template = 'plotly_dark')
fig.show()

最简单的方法是用 curve_type = 'normal' 构建另一个图形 fig2 并使用以下方法从那里获取值:

fig2 = ff.create_distplot(hist_data, group_labels, curve_type = 'normal')
normal_x = fig2.data[1]['x']
normal_y = fig2.data[1]['y']

然后使用 fid.add_trace(go.Scatter()) 在第一个 fig 中包含这些值,如下所示:

fig2 = ff.create_distplot(hist_data, group_labels, curve_type = 'normal')
normal_x = fig2.data[1]['x']
normal_y = fig2.data[1]['y']
fig.add_traces(go.Scatter(x=normal_x, y=normal_y, mode = 'lines',
                          line = dict(color='rgba(0,255,0, 0.6)',
                                      #dash = 'dash'
                                      width = 1),
                          name = 'normal'
                         ))
fig.show()

绘制两条密度曲线: