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

How to label a grouped bar chart using plotly express?

我想在 plotly express 的条形图顶部添加数据标签。我正在使用数据框中的两个不同列,所以我不能使用“颜色”方法。我想为每个栏定义“文本”,以便它在栏的顶部显示数据。这是一个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()

我试过了:

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

但这行不通。

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

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

结果:

完整代码:

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

我找到了更好的答案。

让我们以这本词典为例:

data_dictionary = {
    "data_frame":{
        "x":["Aaron", "Bob", "Chris"],
        "y1":[5, 10, 6],
        "y2":[8, 16, 12]
    },
    "x":"x",
    "y":["y1", "y2"],
    "barmode":"group",
    "text":None,
    "text_auto":True
}

之后让我们创建一个图形:

fig = px.bar(
    **data_dictionary
)

如果您输入 fig.show(),您将看到与 vestland 的图表类似的图表。

您唯一需要做的就是将文本设置为 None 并将 text_auto 设置为 True。

希望对你有所帮助。