You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改px.timeline及go.bar的文本颜色、字体与粗细?

修改Plotly px.timeline和go.bar中的文本样式(大小、字体、粗体)

一、px.timeline的文本样式修改

针对你提供的px.timeline代码,要调整图中各类文本(包括timeline标注文本、轴标签、图例等)的样式,可通过update_traces和update_layout方法实现:

1. 修改timeline上的标注文本样式

在你的代码基础上,添加update_traces配置文本的大小、字体和粗体属性:

import pandas as pd
import plotly.express as px
import plotly.subplots as sp

df1 = pd.DataFrame([
dict(unit='MVT',Task="Job A", Start='2009-01-01', Finish='2009-02-28'),
dict(unit='MVT',Task="Job B", Start='2009-02-28', Finish='2009-04-15'),
dict(unit='MVT',Task="Job A", Start='2009-04-15', Finish='2009-05-30')
])

fig1 = px.timeline(df1, x_start="Start", x_end="Finish",y="unit",color="Task",text="unit")
# 设置timeline标注文本:14号Arial字体、粗体
fig1.update_traces(textfont=dict(size=14, family="Arial", weight="bold"))

2. 修改轴标签、图例等全局文本样式

若要调整坐标轴标题、图例的样式,使用update_layout进行全局配置:

fig1.update_layout(
    # Y轴标题样式:16号粗体
    yaxis_title=dict(font=dict(size=16, weight="bold")),
    # X轴标题样式:16号粗体
    xaxis_title=dict(font=dict(size=16, weight="bold")),
    # 图例标题样式:14号粗体
    legend_title=dict(font=dict(size=14, weight="bold")),
    # 图例项文本样式:12号
    legend=dict(font=dict(size=12))
)

fig1.show()

二、go.bar的文本样式修改

对于plotly.graph_objects的Bar图,同样可通过update_traces和update_layout设置文本样式:

import plotly.graph_objects as go

# 创建基础柱形图
fig = go.Figure(data=[
    go.Bar(name='A组', x=['周一', '周二'], y=[10, 15], text=['10', '15'], textposition='auto'),
    go.Bar(name='B组', x=['周一', '周二'], y=[12, 18], text=['12', '18'], textposition='auto')
])

# 修改柱形图上的标注文本:14号微软雅黑、粗体
fig.update_traces(textfont=dict(size=14, family="微软雅黑", weight="bold"))

# 修改轴标签、图例全局样式
fig.update_layout(
    xaxis_title=dict(font=dict(size=16, weight="bold")),
    yaxis_title=dict(font=dict(size=16, weight="bold")),
    legend_title=dict(font=dict(size=14, weight="bold"))
)

fig.show()

关键参数说明

  • textfont中的size控制文本大小,family指定字体(如Arial、微软雅黑),weight设为"bold"即可实现粗体效果。
  • 全局文本样式通过update_layout中对应轴、图例参数的font属性配置。

内容的提问来源于stack exchange,提问作者Johann

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:25:26