Search code examples
pythonaltair

How can I apply clipping to mark_text() in altair?


I have my plot clipped so it only shows certain ranges on the y axis. I added text to it using this code:

text2 = plot2.mark_text(align='left', dx=5, dy= -8, size = 15).encode(text = alt.Text('Accuracy', format = ',.2f'))

But this added annotation appears outside of the plot. So I need to get rid of it.

In the plot, I'm using sth like this:clip = True in mark_line().


Solution

  • You need to set clip=True for the text mark explicitly:

    df = pd.DataFrame({'x': [1, 3], 'y': [1, 4], 'text': ['a', 'b']})
    
    chart = alt.Chart(df).mark_line(clip=True).encode(
        x=alt.X('x', scale=alt.Scale(domain=[0, 2])),
        y='y'
    )
    chart + chart.mark_text().encode(text='text')
    

    enter image description here

    chart + chart.mark_text(clip=True).encode(text='text')
    

    enter image description here