如何使用plotlyexpress标记分组条形图?

nat*_*_22 5 python plotly plotly-python

我想在绘图表达中将数据标签添加到条形图的顶部。我使用数据框中的两个不同列,因此无法使用“颜色”方法。我想为每个栏定义“文本”,以便它在栏顶部显示数据。这是一个 MRE。

import pandas as pd
import plotly.express as px

x = ['Aaron', 'Bob', 'Chris']
y1 = [5, 10, 6]
y2 = [8, 16, 12]

fig = px.bar(x=x, y=[y1,y2],barmode='group')
fig.show()
Run Code Online (Sandbox Code Playgroud)

我试过:

fig = px.bar(x=x, y=[y1,y2],text=[y1,y2], barmode='group')
Run Code Online (Sandbox Code Playgroud)

但这行不通。

ves*_*and 8

使用您的设置,只需将以下内容添加到组合中:

texts = [y1, y2]
for i, t in enumerate(texts):
    fig.data[i].text = t
    fig.data[i].textposition = 'outside'
Run Code Online (Sandbox Code Playgroud)

结果:

在此输入图像描述

完整代码:

import pandas as pd
import plotly.express as px

x = ['Aaron', 'Bob', 'Chris']
y1 = [5, 10, 6]
y2 = [8, 16, 12]

fig = px.bar(x=x, y=[y1,y2],barmode='group')

texts = [y1, y2]
for i, t in enumerate(texts):
    fig.data[i].text = t
    fig.data[i].textposition = 'outside'
fig.show()
Run Code Online (Sandbox Code Playgroud)