Plotly在堆积条上显示总数

时间:2017-02-24 23:34:05

标签: python visualization plotly

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

我可以悬停并查看每个组的各个值,但不是总数。

2 个答案:

答案 0 :(得分:3)

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

enter image description here

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)

答案 1 :(得分:3)

以下是我将总计添加到按条码堆积的条形图中的方法:

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