Plotly (python) : 如何在条形图中添加多个文本标签

Plotly (python) : How to add more then one text label in a bar chart

在下面的代码中,我有一个包含 4 列的数据框('data'、'valor'、'nome' 和 'total')。变量 'text' 将列 'nome' 设置为标签。现在我需要对列 'total' 执行相同操作,我也需要将列 'total' 设置为标签。但是我想不通。

  def bar_detalhado(dframe):
                    import plotly.express as px
                    import plotly

                    df = dframe
                    fig = px.bar(df, x="data", y="valor", text="nome",
                                 color='tipo', barmode='group',
                                 height=400)
                    fig.show()

类似...:

def bar_detalhado(dframe):
                        import plotly.express as px
                        import plotly
    
                        df = dframe
                        fig = px.bar(df, x="data", y="valor", text="nome", text2="total",
                                     color='tipo', barmode='group',
                                     height=400)
                        fig.show()

文档指出您不能指定多于一列,但您可以传递一个字符串列表。

这是一个独立的小示例,它在列表理解中使用 df.itertuples 为每个栏创建一个文本字符串。

import plotly.express as px
import pandas as pd

df = pd.DataFrame(dict(data=[1, 2, 3], valor=[5, 6, 7], nome=[8, 9, 10]))
df['total'] = df.sum(axis=1)
df


def bar_detalhado(dframe):
    fig = px.bar(
        dframe, 
        x="data", 
        y="valor", 
        text=[f"n={row[2]}  v={row[1]}  t={row[3]}" for row in df.itertuples()],
    )
    fig.show()

bar_detalhado(df)