情节:如何制作3D堆叠直方图? [英] Plotly: How to make a 3D stacked histogram?
问题描述
我成功使用 plotly 绘制了几个直方图,如下所示:
I have several histograms that I succeded to plot using plotly like this:
fig.add_trace(go.Histogram(x=np.array(data[key]), name=self.labels[i]))
我想创建类似此3D堆叠直方图的东西,但是要有所不同里面的每个2D直方图都是真实的直方图,而不仅仅是硬编码的行(我的数据的格式为[0.5 0.4 0.5 0.7 0.4]
,因此直接使用直方图非常方便)
I would like to create something like this 3D stacked histogram but with the difference that each 2D histogram inside is a true histogram and not just a hardcoded line (my data is of the form [0.5 0.4 0.5 0.7 0.4]
so using Histogram directly is very convenient)
请注意,我要问的内容与 this 类似,因此也与与此相同.在matplotlib示例中,数据直接以2D数组形式显示,因此直方图是第3维.就我而言,我想提供一个包含许多已经计算出的直方图的函数.
Note that what I am asking is not similar to this and therefore also not the same as this. In the matplotlib example, the data is presented directly in a 2D array so the histogram is the 3rd dimension. In my case, I wanted to feed a function with many already computed histograms.
推荐答案
下面的代码段同时负责图形的装箱和格式设置,因此它使用多个go.Scatter3D
和np.Histogram
痕迹显示为堆叠的3D图表.
输入是使用np.random.normal(50, 5, size=(300, 4))
具有随机数的数据框
如果您可以使用此方法,我们可以详细讨论其他细节:
The snippet below takes care of both binning and formatting of the figure so that it appears as a stacked 3D chart using multiple traces of go.Scatter3D
and np.Histogram
.
The input is a dataframe with random numbers using np.random.normal(50, 5, size=(300, 4))
We can talk more about the other details if this is something you can use:
图1:角度1
图2:角度2
完整代码:
# imports
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import plotly.io as pio
pio.renderers.default = 'browser'
# data
np.random.seed(123)
df = pd.DataFrame(np.random.normal(50, 5, size=(300, 4)), columns=list('ABCD'))
# plotly setup
fig=go.Figure()
# data binning and traces
for i, col in enumerate(df.columns):
a0=np.histogram(df[col], bins=10, density=False)[0].tolist()
a0=np.repeat(a0,2).tolist()
a0.insert(0,0)
a0.pop()
a1=np.histogram(df[col], bins=10, density=False)[1].tolist()
a1=np.repeat(a1,2)
fig.add_traces(go.Scatter3d(x=[i]*len(a0), y=a1, z=a0,
mode='lines',
name=col
)
)
fig.show()
这篇关于情节:如何制作3D堆叠直方图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!