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

标签 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

最佳答案

叠加图

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

相关文章:

R - plotly 错误对象...未找到

python - 连续字符后出现意外字符

python - 随机使用不同的代理和用户代理进行智能屏幕抓取?

python - 'from pylons import config' 和 'import pylons.config' 之间的区别

python - 在 python 中将字符串转换为数组的最快方法是什么?

python - 使用 for 循环在子图中绘制箱形图

r - 在 Shiny 应用程序中旋转 3D 散点图

python - 如何处理异常,同时在 python 中附加一个列表,其中包含从存储从 .json 文件读取的数据的字典中读取的数据?

python - 颜色条最小值和最大值

Python Dash 绘图 : Show default closest data on hover or compare data on hover in graph