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

时间:2019-01-12 17:33:40

标签: python plotly

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

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

1 个答案:

答案 0 :(得分:3)

叠图

只需将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