Plotly graph_objects实现条形图标题部分文字颜色修改
Plotly条形图标题部分文字着色解决方案
你用ANSI转义码给标题着色的方式只适用于终端输出,Plotly的图表标题支持的是HTML/CSS样式,所以得换用HTML标签来实现部分文字着色。
修改后的代码
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)' )) # 用HTML标签实现部分文字着色 title = 'This is black text <span style="color:rgb(223,16,103)">this is a highlight</span>.' 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)
关键说明
- Plotly的标题文本会自动解析HTML内容,用
<span>标签包裹需要着色的文字,通过style属性设置color为目标RGB值(和条形颜色一致)即可。 - 不需要像终端那样用重置码,HTML标签闭合后就会恢复默认样式。
这样修改后,图表标题里的指定文字就会显示和条形相同的粉色,其余文字保持默认颜色,和你print的预期效果一致。
内容的提问来源于stack exchange,提问作者earths_wizard
相关产品推荐
相关产品推荐

