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

如何在Plotly柱状图中将X轴刻度替换为自定义标签?

自定义Plotly X轴刻度标签的实现方法

嘿,我来帮你搞定这个自定义X轴刻度标签的事儿!针对你用Plotly Express画柱状图的场景,有两种很直观的方式来替换X轴的刻度标签,不用大改现有代码:

方法1:直接修改DataFrame的对应列(最省心)

如果你的Area_Name列里的原始值不是你想要的显示文本,直接先把这个列的内容替换成自定义标签,再调用px.bar就行——因为Plotly Express默认会把X轴对应列的内容作为刻度标签。

示例代码:

# 先给df2的Area_Name列替换成自定义标签,按你的实际数据长度调整列表内容
df2['Area_Name'] = ['Area1', 'Area2', 'Area3', 'Area4']

# 然后正常执行你原来的绘图代码
fig = px.bar(df2, x='Area_Name', y='Per_User_Averge_Download_Speed_Mbp', 
             hover_data=['Users_in_Area', 'Per_User_Averge_Download_Speed_Mbp'], 
             color='Per_User_Averge_Download_Speed_Mbp', height=400, 
             color_continuous_scale=px.colors.qualitative.Antique, 
             labels=dict( Area_Name="Area", 
                         Per_User_Averge_Download_Speed_Mbp="Download Speed/(Mbps)", 
                         Users_in_Area="User Count") )
fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True, 
                 tickangle=-90, tickfont=dict(family='Rockwell', color='crimson', size=14))
fig.show()

方法2:通过update_xaxes手动指定刻度映射(不修改原数据)

如果你不想改动原始DataFrame,就在update_xaxes里添加tickvals和ticktext两个参数:

  • tickvals:对应X轴原来的刻度值(也就是df2['Area_Name']的原始内容)
  • ticktext:你想要显示的自定义标签列表,顺序要和tickvals完全对应

示例代码:

# 定义自定义标签列表,按实际数据长度调整
custom_labels = ['Area1', 'Area2', 'Area3']

# 你的原始绘图代码不变
fig = px.bar(df2, x='Area_Name', y='Per_User_Averge_Download_Speed_Mbp', 
             hover_data=['Users_in_Area', 'Per_User_Averge_Download_Speed_Mbp'], 
             color='Per_User_Averge_Download_Speed_Mbp', height=400, 
             color_continuous_scale=px.colors.qualitative.Antique, 
             labels=dict( Area_Name="Area", 
                         Per_User_Averge_Download_Speed_Mbp="Download Speed/(Mbps)", 
                         Users_in_Area="User Count") )

# 在update_xaxes里追加tickvals和ticktext参数
fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True, 
                 tickangle=-90, tickfont=dict(family='Rockwell', color='crimson', size=14),
                 tickvals=df2['Area_Name'],  # 绑定原始刻度值
                 ticktext=custom_labels)     # 设置自定义显示文本
fig.show()

两种方法都能实现你的需求,选哪种看你是否需要保留原始DataFrame的内容~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:10:10