在堆积条形图上显示总数

Showing total on stacked bar Plotly

如何在 Plotly 中的堆叠条形图上显示总数。

我可以将鼠标悬停并查看每个组的单个值,但看不到总值。

您可以在 text 属性中设置总和并在 hoverinfo 中显示。

import plotly
plotly.offline.init_notebook_mode()

animals = ['giraffes', 'orangutans', 'monkeys']
zoo_sf = [20, 14, 23]
zoo_la = [12, 18, 29]

trace1 = plotly.graph_objs.Bar(
    x=animals,
    y=zoo_sf,
    name='SF Zoo',
    hoverinfo='text',
    text=[('Total: ' + str(x + y) + '<br>SF: ' + str(y)) for x, y in zip(zoo_la, zoo_sf)] 
)

trace2 = plotly.graph_objs.Bar(
    x=animals,
    y=zoo_la,
    name='LA Zoo',
    hoverinfo='text',
    text=[('Total: ' + str(x + y) + '<br>LA: ' + str(x)) for x, y in zip(zoo_la, zoo_sf)]
)

data = [trace1, trace2]
layout = plotly.graph_objs.Layout(barmode='stack')
fig = plotly.graph_objs.Figure(data=data, layout=layout)
plotly.offline.iplot(fig)

以下是我如何将总计添加到堆叠条形图:

x_labels = ['giraffes', 'orangutans', 'monkeys']
totals = [32, 32, 52]

trace1 = go.Bar(
    x=x_labels,
    y=[20, 14, 23],
    text=[20, 14, 23],
    name='SF Zoo'
)
trace2 = go.Bar(
    x=x_labels,
    y=[12, 18, 29],
    text=[12, 18, 29],
    name='LA Zoo'
)

data = [trace1, trace2]
layout = go.Layout(
    barmode='stack',
    plot_bgcolor='rgba(0,0,0,0)'
)

total_labels = [{"x": x, "y": total*1.05, "text": str(total), "showarrow": False} for x, total in zip(x_labels, totals)]
fig = go.Figure(data=data, layout=layout)
fig = fig.update_layout(annotations=total_labels)

fig.show()

plotly bar chart