Plotly graph_objects 仅更改部分文本的字体颜色

问题描述 投票:0回答:1

我正在尝试在 Plotly 中制作条形图,并希望部分标题与条形图具有相同的颜色,但不是所有文本。

这是我迄今为止所尝试过的。打印显示了我希望得到的东西。

import pandas as pd
import plotly.graph_objects as go

def create_barchart(df):
    fig = go.Figure()
    fig.add_trace(go.Bar(
        x=df["value"],
        y=df["col_name"],
        orientation="h",
        showlegend=False,
        marker_color='rgb(223,16,103)'
    ))
            
    def rgb(r, g, b):
        """
        RGB text (from @MiloCat's example)
        """
        return f"\033[38;2;{r};{g};{b}m"

    pink = rgb(223,16,103)

    reset = "\033[0m" # Important!
    title = f'This is black text {pink} this is a highlight {reset}.'
    print(title)
    
    fig.update_layout(
        title={"text": title},
    )

    fig.show()

df = pd.DataFrame({'col_name': ['A', 'B', 'C', 'D', 'E', 'F'], 'value':[123, 34, 54, 87, 98, 102]})
create_barchart(df)
python pandas dataframe plotly
1个回答
0
投票

发布来自 @HMH1013 和 @Lourenco 答案的工作解决方案


    import pandas as pd
    import plotly.graph_objects as go
    
    df = pd.DataFrame({'col_name': ['A', 'B', 'C', 'D', 'E', 'F'], 'value':[123, 34, 54, 87, 98, 102]})
    
    pink_color='#D51067'
    
    def create_barchart(df):
        fig = go.Figure()
        fig.add_trace(go.Bar(
            x=df["value"],
            y=df["col_name"],
            orientation="h",
            showlegend=False,
            marker_color=pink_color
        ))
    
        fig.update_layout(
            title={"text": f'This is black text <span style="color:{pink_color}">this is a highlight</span>.'},
        )
    
        fig.show()
    
    create_barchart(df)

© www.soinside.com 2019 - 2024. All rights reserved.