gpt4 book ai didi

python - Plotly - 如何在单个图中复制相同的直方图

转载 作者:太空宇宙 更新时间:2023-11-03 15:37:18 25 4
gpt4 key购买 nike

如何在下面的另一行显示相同的图表?

import plotly.offline as py
import plotly.graph_objs as go
import numpy as np

x0 = np.random.normal(loc=0, scale=1, size=1000)
x1 = np.random.normal(loc=0.1, scale=0.2, size=100)

trace0 = go.Histogram(
x=x0
)
trace1 = go.Histogram(
x=x1
)
data = [trace0, trace1]


layout = go.Layout(barmode='stack')
fig = go.Figure(data=data, layout=layout)

py.plot(fig, filename='stacked histogram')

我想从中得到一个图中的单个直方图:

enter image description here

对于这个结果,两个相同的直方图堆叠在同一个图中:

enter image description here

enter image description here

最佳答案

叠加图

只需将 barmode = 'stack' 替换为 'overlay'。我将不透明度设置为 0.6,以便两个直方图可见:

import plotly.offline as py
import plotly.graph_objs as go
import numpy as np

x0 = np.random.normal(loc=0, scale=1, size=1000)
x1 = np.random.normal(loc=0.1, scale=0.2, size=100)
trace0 = go.Histogram(
x=x0,
opacity=0.6
)
trace1 = go.Histogram(
x=x1,
opacity=0.6
)
data = [trace0, trace1]
layout = go.Layout(barmode='overlay')
fig = go.Figure(data=data, layout=layout)
py.plot(fig, filename='overlaid histogram')

此代码返回以下图:

enter image description here

支线

如果您想要在 2x1 网格中重复相同的绘图,那么您可以使用子图以绘图方式实现它:

import plotly.offline as py
import plotly.graph_objs as go
import numpy as np
from plotly import tools

x0 = np.random.normal(loc=0, scale=1, size=1000)
x1 = np.random.normal(loc=0.1, scale=0.2, size=100)
trace0 = go.Histogram(
x=x0,
opacity=0.6,
name='trace 0',
marker={'color':'#1f77b4'}
)
trace1 = go.Histogram(
x=x1,
opacity=0.6,
name='trace 1',
marker={'color':'#ff7f0e'}
)

fig2 = tools.make_subplots(rows=2, cols=1, subplot_titles=('One', 'Two'))
fig2.append_trace(trace0, 1, 1)
fig2.append_trace(trace1, 1, 1)
fig2.append_trace(trace0, 2, 1)
fig2.append_trace(trace1, 2, 1)

fig2.layout['barmode'] = 'overlay'
py.plot(fig2, filename='subplots')

您需要指定名称和颜色以确保获得相同的图。要在每个子图中获得堆叠或重叠的直方图或其他任何内容,只需在图形的布局中指定即可。例如,为了获得叠加直方图,我在上面执行了 fig2.layout['barmode'] = 'overlay'

这将为您提供以下内容:

enter image description here

关于python - Plotly - 如何在单个图中复制相同的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54162174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com