有没有办法使用 Altair 标签自动换行或插入换行符?

Is there a way to word wrap or insert a line break with Altair labels?

有没有办法在 Altair 中显示较长的标签时插入换行符?

d = {'source': ['short label', 'a longer label that needs a line break', 'short label', 'a longer label that needs a line break'], 'variable': ['begin','begin','end','end'], 'value':[75, 25, 20, 80]}
df = pd.DataFrame(data=d)

slope = alt.Chart(df).mark_line().encode(x='variable:N',y=alt.Y('value:Q',scale=alt.Scale(domain=(0,100))),color='source')
text = slope.mark_text(align='left',baseline='middle').encode(text='source:N')
(slope + text).properties(width=200)`

我看到一个 的标题,但我无法将其用于标签。

我找到了适合我的目的的解决方法。我调整了数据框,将较长的标签分成两部分,并使用 dx/dy 调整将它们移动到位。

d = {'source1': ['short label', 'a longer label that', 'short label', 'a longer label that']
,'source2': ['', 'needs a line break', '', 'needs a line break']
,'variable': ['begin','begin','end','end']
,'value':[75, 25, 20, 80]}

df = pd.DataFrame(data=d)

print(df)

               source1             source2 variable  value
0          short label                        begin     75
1  a longer label that  needs a line break    begin     25
2          short label                          end     20
3  a longer label that  needs a line break      end     80



slope = alt.Chart(df).mark_line().encode(x='variable:N',y=alt.Y('value:Q',scale=
        alt.Scale(domain=(0,100)),axis=alt.Axis(grid=False)),
        color=alt.Color('source1',legend=None))
text1 = slope.mark_text(align='left',baseline='middle', dx=10).encode(text='source1:N')
text2 = slope.mark_text(align='left',baseline='middle', dx=10, dy=10).encode(text='source2:N')

(slope + text1 + text2).properties(width=500)

对于此特定示例,您可以向需要换行的标签添加换行符:'a longer label that \nneeds a line break',然后更改 mark_text 中的参数以包含 lineBreak=r'\n'

d = {'source': ['short label', 'a longer label that \nneeds a line break', 'short label', 'a longer label that \nneeds a line break'], 'variable': ['begin','begin','end','end'], 'value':[75, 25, 20, 80]}
df = pd.DataFrame(data=d)

slope = alt.Chart(df).mark_line().encode(x='variable:N',y=alt.Y('value:Q',scale=alt.Scale(domain=(0,100))),color='source')
text = slope.mark_text(align='left',baseline='middle', lineBreak=r'\n').encode(text='source:N')
(slope + text).properties(width=500)