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

标签 python r bar-chart plotly

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

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

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 Example Image

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

最佳答案

这有点 hackish,但它完成了工作。

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

Barchart

关于python - Plotly 中条形图的单独标记条,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33873298/

相关文章:

python - 使用正则表达式查找函数调用

Python 函数作为后台进程运行

Python 堆叠链表

r - 使用 dplyr 聚合不在组中的值

javascript - C3 带百分比的图表栏

python - 如何在 Python Plotnine barplot 中更改 y 轴以显示百分比 (%)?

python - 如何为特定行和列中的numpy数组赋值

r - RTextTools 中的 Create_Analytics

r - 如何在 R 中与 litR 并行处理 LAScatalog

android - AChart 引擎条形图显示不正确