Search code examples
pythonaltair

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


Is there a way to insert a line break when displaying longer labels in 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)`

I see a list of arrays in an option for a title but I haven't been able to get that to work for labels.


Solution

  • For this particular example, you could add a new line character to the label that needs the new line: 'a longer label that \nneeds a line break' and then change the parameters inside mark_text to include 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)
    

    enter image description here