Plotting a second axis with percentage on a histogram plotly chart

Viewed 1157

I have plotted a histogram using plotly and the following code;

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

from plotly.offline import init_notebook_mode
plotly.offline.init_notebook_mode(connected=True)

x0 = np.random.randn(500)
x1 = np.random.randn(500)+1

trace1 = go.Histogram(
    x=x0
)
trace2 = go.Histogram(
    x=x1
)

data = [trace1, trace2]
layout = go.Layout(barmode='stack')
fig = go.Figure(data=data, layout=layout)

plotly.offline.plot(fig)

What I would like to add is the percentage of the total on the right hand side of the chart as a second axis.

1 Answers

I don't know if there's any other way but I can think of adding a phantom trace as a workaround:

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

from plotly.offline import init_notebook_mode
plotly.offline.init_notebook_mode(connected=True)

x0 = np.random.randn(500)
x1 = np.random.randn(500)+1

trace1 = go.Histogram(
    x=x0
)
trace2 = go.Histogram(
    x=x1
)
phantom_trace = go.Histogram(
    x=np.hstack([x1, x0]),
    histnorm='percent',
    yaxis='y2',
    showlegend=False,
    hoverinfo='skip',
    marker=go.histogram.Marker(color='rgba(0,0,0,0)')
)

data = [trace1, trace2, phantom_trace]
layout = go.Layout(
    barmode='stack',
    yaxis2=go.layout.YAxis(
        side='right',
        overlaying='y1',
        ticksuffix='%'
    )
)
fig = go.Figure(data=data, layout=layout)

plotly.offline.plot(fig)
Related