用plotlyexpress重叠两个直方图

问题描述 投票:0回答:3

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

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()

纯粹的情节,就是这样,从文档复制:

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()

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

plotly plotly-express
3个回答
31
投票

诀窍是通过将数据组合成一个整洁的数据框来制作单个 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")

产量:


3
投票

您可以获取 px 结构并使用它来创建图形。我希望使用 Express 中的“颜色”选项来显示堆叠直方图,但很难以纯绘图方式重新创建。

给定一个数据帧(df),其中 utctimestamp 作为时间索引,严重性和类别作为直方图中要计数的内容,我用它来获取堆叠直方图:

figure_data=[]
figure_data.extend([i for i in px.histogram(df, x="utctimestamp", color="severity", histfunc="count").to_dict()['data']])
figure_data.extend([i for i in px.histogram(df, x="utctimestamp", color="category", histfunc="count").to_dict()['data']])
fig=go.Figure(figure_data)
fig.update_layout(barmode='stack')
fig.update_traces(overwrite=True, marker={"opacity": 0.7}) 
fig.show()

tl;dr

px.histogram
创建一个直方图对象列表,您可以将其作为列表抓取并通过
go.Figure
进行渲染。

我无法内联发布,但这里有来自 px 的堆叠直方图https://i.stack.imgur.com/X0dyy.jpg


3
投票

如果想要使用plotly的

graph_objects
模块,可以使用
barmode="overlay"
来代替,如下所示的2个直方图。

import plotly.graph_objects as go
fig = go.Figure(data=[go.Histogram(x=x)])
fig.add_trace(go.Histogram(x=x,))
fig.update_layout(barmode='overlay')

© www.soinside.com 2019 - 2024. All rights reserved.