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

2022-01-21 00:00:00 python plotly r bar-chart

问题描述

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

我尝试对教程中的示例进行简单的修改来实现这一点,如下:

import plotly.plotly as py导入 plotly.graph_objsx = ['产品 A'、'产品 B'、'产品 C']y1 = [20, 14, 23]y2 = [12, 18, 29]注释1 = [字典(x=xi,y=yi,文本=str(yi),xanchor='自动',yanchor='底部',显示箭头=假,) 对于 xi, yi in zip(x, y1)]注释2 = [字典(x=xi,y=yi,文本=str(yi),xanchor='自动',yanchor='底部',显示箭头=假,) 对于 xi, yi in zip(x, y2)]注释 = 注释 1 + 注释 2trace1 = go.Bar(x=x,y=y1,名称='SF动物园')trace2 = go.Bar(x=x,y=y2,名称='洛杉矶动物园')数据 = [trace1,trace2]布局=去.布局(barmode='组',注释=注释)fig = go.Figure(数据=数据,布局=布局)plot_url = py.plot(fig, filename='stacked-bar')

产生这个情节:

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

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

相关文章