在直方图绘图图中用百分比绘制第二个轴

时间:2019-06-18 16:02:52

标签: python histogram plotly

我已使用plotly和以下代码绘制了直方图;

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)

我要添加的是图表右侧作为第二轴的总数的百分比。

1 个答案:

答案 0 :(得分:0)

我不知道是否还有其他方法,但是我可以考虑添加幻像跟踪作为解决方法:

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)