Plotly中条形图的单独标记的条 [英] Individually labeled bars for bar graph in Plotly

查看:154
本文介绍了Plotly中条形图的单独标记的条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为分组的条形图创建批注-每个条形图都有一个特定的数据标签,该标签显示该条形图的值并且位于条形图的中心上方.

I was trying to create annotations for grouped bar charts - where each bar has a specific data label that shows the value of that bar and is located above the centre of the bar.

我尝试对教程中的示例进行简单的修改以实现此目的,如下所示:

I tried a simple modification of the examples in tutorial to achieve this, as follows:

import plotly.plotly as py
import plotly.graph_objs as go

x = ['Product A', 'Product B', 'Product C']
y1 = [20, 14, 23]
y2 = [12, 18, 29]

annotations1 = [dict(
            x=xi,
            y=yi,
            text=str(yi),
            xanchor='auto',
            yanchor='bottom',
            showarrow=False,
        ) for xi, yi in zip(x, y1)]
annotations2 = [dict(
            x=xi,
            y=yi,
            text=str(yi),
            xanchor='auto',
            yanchor='bottom',
            showarrow=False,
        ) for xi, yi in zip(x, y2)]
annotations = annotations1 + annotations2

trace1 = go.Bar(
    x=x,
    y=y1,
    name='SF Zoo'
)
trace2 = go.Bar(
    x=x,
    y=y2,
    name='LA Zoo'
)
data = [trace1, trace2]
layout = go.Layout(
    barmode='group',
    annotations=annotations
)
fig = go.Figure(data=data, layout=layout)
plot_url = py.plot(fig, filename='stacked-bar')

是哪个情节产生的: https://plot.ly/~ashish.baghudana/49 .embed

Which produces this plot: https://plot.ly/~ashish.baghudana/49.embed

但是,数据标签不是位于单个条形的中心,而是位于每个条形的中心.我想知道是否有解决方法,而不是手动注释.

However,the data labels are not centred over individual bars, but over the centre of each group of bars. I was wondering if there is a workaround to this, rather than annotating manually.

推荐答案

这有点黑,但可以完成工作.

This is slightly hackish, but it gets the job done.

x = ['Product A', 'Product B', 'Product C']
y1 = [20, 14, 23]
y2 = [12, 18, 29]

xcoord = [0,1,2]

annotations1 = [dict(
            x=xi-0.2,
            y=yi,
            text=str(yi),
            xanchor='auto',
            yanchor='bottom',
            showarrow=False,
        ) for xi, yi in zip(xcoord, y1)]

annotations2 = [dict(
            x=xi+0.2,
            y=yi,
            text=str(yi),
            xanchor='auto',
            yanchor='bottom',
            showarrow=False,
        ) for xi, yi in zip(xcoord, y2)]

annotations = annotations1 + annotations2

这篇关于Plotly中条形图的单独标记的条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆