Plotly 中条形图的单独标记的条形

2023-12-26

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

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

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')

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

但是,数据标签不是在各个条形上居中,而是在每个条形的中心上居中group酒吧。我想知道是否有解决方法,而不是手动注释。


这有点骇人听闻,但它可以完成工作。

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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Plotly 中条形图的单独标记的条形 的相关文章

随机推荐