Plotly go.Bar : 根据值添加自定义图例标签

Plotly go.Bar : Add custom legend labels based on values

我有一个数据框,其中一列包含正值和负值。我正在使用 plotly barplot,我想根据值自定义图例标签。

这是一个模拟 pandas DataFrame:

df = pd.DataFrame({'Date': [07-2020, 08-2020, 09-2020, 10-2020],
                   'Value': [3, -2, 4, -1] })

df["Color"] = np.where(df["Value"]<0, 'rgb(0,0,255)', 'rgb(255,0,0)')
df["Name"] = np.where(df["Value"]<0, 'Low', 'High')


    fig = go.Figure(

        data=[

              go.Bar(
                        x=df["Date"],
                        y=df["Value"],
                        color=df['Name'],
                        marker_color=df['Color']
                    ),

              ],

        layout=go.Layout(

        

            xaxis=dict(
                tickangle=60,
                tickfont=dict(family="Rockwell", color="crimson", size=14)
            ),

            yaxis=dict(
                title="Net Change",
                showticklabels=True
            ),

            barmode="stack",

        )
    )

如何在值为负时添加图例标签 Low,在值为正时添加 High

我不确定您的图例标签是图例标签还是注释标签,所以我添加了对两者的支持。注释条形图,可以在文本中指定显示位置,会自动确定位置。为了给图例添加高和低,我创建了一个高数据框和一个低数据框,并给每个数据框起了一个名字。作为布局,我们指定刻度位置和显示名称,以便按数据框顺序排列它们。

import pandas as pd
import plotly.graph_objects as go
import numpy as np

df = pd.DataFrame({'Date': ['07-2020', '08-2020', '09-2020', '10-2020'], 'Value': [3, -2, 4, -1] })

df["Color"] = np.where(df["Value"]<0, 'rgb(0,0,255)', 'rgb(255,0,0)')
df["Name"] = np.where(df["Value"]<0, 'Low', 'High')

df_high = df[df['Name'] == 'High']
df_Low = df[df['Name'] == 'Low']

fig = go.Figure(data=[
    go.Bar(
        x=[0,2],
        y=df_high["Value"],
        text=df_high["Name"],
        textposition='auto',
        name='High',
        marker_color=df_high['Color']
    ),],)

fig.add_trace(
    go.Bar(
        x=[1,3],
        y=df_Low["Value"],
        text=df_Low["Name"],
        textposition='auto',
        name='Low',
        marker_color=df_Low['Color'])
             )
                
fig.update_layout(
    xaxis=dict(
        tickangle=60,
        tickfont=dict(family="Rockwell", color="crimson", size=14),
        tickvals=[0,1,2,3],
        ticktext=df['Date']
    ),
    yaxis=dict(
        title="Net Change",
        showticklabels=True
    ),
    barmode="stack",
)
    
fig.show()