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

如何在Python Altair中为y轴每个标签添加边框

解决方案

你要实现y轴每个标签对应行的分隔边框,最贴合预期效果的实现方式是叠加矩形背景图层,修改后的完整代码如下:

import altair as alt

# 新增底图层:每个y类别对应带边框的矩形
base_layer = alt.Chart(q4df).mark_rect(
    fill='white',
    stroke='#cccccc',
    strokeWidth=1
).encode(
    y = alt.Y('TITLE', title=None),
    x = alt.value(0),
    x2 = alt.value(400) # 和你设置的图表宽度保持一致
)

# 原有散点图层,保留所有原始配置
dot_layer = alt.Chart(q4df).transform_fold(
  rosspaints,
  as_=['column', 'value']
).mark_circle().encode(
  x = alt.X('column:N', axis=None),
  y = alt.Y('TITLE', title=None),
  size = alt.Size('value:Q', legend=None),
  color=alt.Color('column:N', legend=None,
                   scale=alt.Scale(
            domain=['alizarin crimson','bright red','burnt umber','cadmium yellow','dark sienna', 
              'indian yellow','indian red','liquid black','liquid clear','black gesso',
              'midnight black','phthalo blue','phthalo green','prussian blue','sap green',
              'titanium white','van dyke brown','yellow ochre'],
            range=['#94261f','#c06341','#614f4b','#f8ed57','#5c2f08','#e6ba25','#cd5c5c',
                '#000000','#ffffff','#000000','#36373c','#2a64ad','#215c2c','#325fa3',
                '#364e00','#f9f7eb','#2d1a0c','#b28426']))
).properties(
    width=400,
    height=700
)

# 两个图层叠加后配置样式
alt.layer(base_layer, dot_layer).configure_axis(
    grid=False,
    labelFontWeight= 'bold',
    labelColor='black'
)

如果不需要完整的行边框,只想用分隔线实现区分效果,可以直接调整y轴网格配置,无需新增图层,修改原有代码的y轴和全局配置即可:

alt.Chart(q4df).transform_fold(
  rosspaints,
  as_=['column', 'value']
).mark_circle().encode(
  x = alt.X('column:N', axis=None),
  y = alt.Y('TITLE', title=None, axis=alt.Axis(grid=True, gridColor='#e0e0e0', gridWidth=1)),
  size = alt.Size('value:Q', legend=None),
  color=alt.Color('column:N', legend=None,
                   scale=alt.Scale(
            domain=['alizarin crimson','bright red','burnt umber','cadmium yellow','dark sienna', 
              'indian yellow','indian red','liquid black','liquid clear','black gesso',
              'midnight black','phthalo blue','phthalo green','prussian blue','sap green',
              'titanium white','van dyke brown','yellow ochre'],
            range=['#94261f','#c06341','#614f4b','#f8ed57','#5c2f08','#e6ba25','#cd5c5c',
                '#000000','#ffffff','#000000','#36373c','#2a64ad','#215c2c','#325fa3',
                '#364e00','#f9f7eb','#2d1a0c','#b28426']))
).properties(
    width=400,
    height=700
).configure_axisX(
    grid=False
).configure_axis(
    labelFontWeight= 'bold',
    labelColor='black'
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:54:04