如何在下面的另一行显示相同的图表?
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')
我想从中得到一个图中的单个直方图:
对于这个结果,两个相同的直方图堆叠在同一个图中:
最佳答案
叠加图
只需将 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')
此代码返回以下图:
支线
如果您想要在 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'
。
这将为您提供以下内容:
关于python - Plotly - 如何在单个图中复制相同的直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54162174/