用 plotly express 叠加两个直方图

mat*_*ter 4 plotly plotly-express

我想使用以下简单的代码叠加两个直方图,我目前只显示一个与另一个相邻的直方图。这两个数据帧的长度不同,但叠加它们的直方图值仍然有意义。

import plotly.express as px

fig1 = px.histogram(test_lengths, x='len', histnorm='probability', nbins=10)
fig2 = px.histogram(train_lengths, x='len', histnorm='probability', nbins=10)
fig1.show()
fig2.show()
Run Code Online (Sandbox Code Playgroud)

纯情节,这是从文档中复制的方式:

import plotly.graph_objects as go

import numpy as np

x0 = np.random.randn(500)
# Add 1 to shift the mean of the Gaussian distribution
x1 = np.random.randn(500) + 1

fig = go.Figure()
fig.add_trace(go.Histogram(x=x0))
fig.add_trace(go.Histogram(x=x1))

# Overlay both histograms
fig.update_layout(barmode='overlay')
# Reduce opacity to see both histograms
fig.update_traces(opacity=0.75)
fig.show()
Run Code Online (Sandbox Code Playgroud)

我只是想知道情节表达是否有任何特别惯用的方式。希望这也能说明 plotly 和 plotly express 之间的完整性和不同层次的抽象。

nic*_*ten 7

诀窍是通过将数据组合成一个整洁的数据框来制作单个 Plotly Express 图形,而不是制作两个图形并尝试将它们组合起来(目前这是不可能的):

import numpy as np
import pandas as pd
import plotly.express as px

x0 = np.random.randn(250)
# Add 1 to shift the mean of the Gaussian distribution
x1 = np.random.randn(500) + 1

df =pd.DataFrame(dict(
    series=np.concatenate((["a"]*len(x0), ["b"]*len(x1))), 
    data  =np.concatenate((x0,x1))
))

px.histogram(df, x="data", color="series", barmode="overlay")
Run Code Online (Sandbox Code Playgroud)

产量:

在此处输入图片说明