简体   繁体   English

在直方图图表上绘制具有百分比的第二轴

[英]Plotting a second axis with percentage on a histogram plotly chart

I have plotted a histogram using plotly and the following code; 我用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)

What I would like to add is the percentage of the total on the right hand side of the chart as a second axis. 我想补充的是图表右侧总数占第二轴的百分比。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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