简体   繁体   中英

Plotly - how to replicate the same histogram in a single plot

How to have this same graph on another row below?

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')

I want to get from this, a single histogram in one plot:

在此输入图像描述

To this result, two of the same histograms stacked in the same plot:

在此输入图像描述

在此输入图像描述

Overlaid plots

Just replace barmode = 'stack' with 'overlay' . I set opacity to 0.6 so that the two histograms are visible:

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')

This code returns the following plot:

在此输入图像描述

Subplots

If what you want is repeat the same plot in a 2x1 grid, then you can achieve it in plotly using subplots:

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')

You need to specify the names and colors to make sure that you'll get the same plot. And to get a stacked or overlaid histogram or whatever on each subplot, simply specify it in the figure's layout. For example, to get an overlaid histogram I did fig2.layout['barmode'] = 'overlay' above.

This will give you the following:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM