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

Plotly多分类柱状图如何隐藏内层标签并旋转外层分类刻度

需求说明

  • 使用plotly.graph-objects绘制多分类柱状图时,不展示内层分类标签
  • 额外需要旋转外层分类的标签

现有代码与效果

初始代码如下:

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
  "City": ["Toronto", "Toronto", "Toronto", "CPH", "CPH", "London", "London"],
  "Tower name": ["T1", "T2", "T3", "T4", "T5", "T6","T7"],
  "Height": [1.0, 1.5, 2.0, 3.0, 4.0, 2.0 ,5.0],
})

fig = go.Figure(go.Bar(x=df.loc[:,["City", "Tower name"]].T.values, y=df["Height"].values))
fig.show()

运行初始代码输出效果:
output
期望输出效果:
desired output

已尝试的无效方案

  • 隐藏内层分类尝试:创建空列设置ticktext,未生效
df['empty'] = ""
fig = go.Figure(go.Bar(x=df.loc[:,["City", "Tower name"]].T.values, y=df["Height"].values))
fig.update_xaxes(ticktext = df['empty'])
fig.show()
  • 旋转刻度尝试:使用tickangle参数仅能旋转内层分类标签,外层城市名称无变化
fig = go.Figure(go.Bar(x=df.loc[:,["City", "Tower name"]].T.values, y=df["Height"].values))
fig.update_xaxes(tickangle = -90)
fig.show()

上述旋转代码运行效果:
output

解决方案

通过手动构造X轴坐标、自定义外层刻度的方式实现需求,不受plotly版本限制,也支持灵活调整分组间距:

import pandas as pd
import plotly.graph_objects as go

df = pd.DataFrame({
  "City": ["Toronto", "Toronto", "Toronto", "CPH", "CPH", "London", "London"],
  "Tower name": ["T1", "T2", "T3", "T4", "T5", "T6","T7"],
  "Height": [1.0, 1.5, 2.0, 3.0, 4.0, 2.0 ,5.0],
})

# 手动计算每个柱子的X坐标、城市分组的刻度位置
x_coords = []
city_tick_pos = {}
current_x = 0
group_gap = 1 # 不同城市分组之间的间距

for city, group in df.groupby("City", sort=False):
    tower_count = len(group)
    # 记录当前城市下所有塔的X坐标
    x_coords.extend(range(current_x, current_x + tower_count))
    # 记录城市标签的居中位置
    city_tick_pos[city] = current_x + (tower_count - 1)/2
    # 移动X坐标起始点,加上分组间距
    current_x += tower_count + group_gap

# 绘图
fig = go.Figure(go.Bar(x=x_coords, y=df["Height"].values))

# 配置X轴:仅展示外层城市标签、旋转角度
fig.update_xaxes(
    tickvals = list(city_tick_pos.values()),
    ticktext = list(city_tick_pos.keys()),
    tickangle = -90
)

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:36:07