Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format text of mark_text in Altair

Tags:

altair

I'm trying to create a chart somewhat along the lines of the Multi-Line Tooltip example, but I'd like to format the string that is being printed to have some text added at the end. I'm trying to modify this part:

# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, 'y:Q', alt.value(' '))
)

Specifically, rather than 'y:Q' I want something along the lines of 'y:Q' + " suffix". I've tried doing something like this:

# Draw text labels near the points, and highlight based on selection
text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, 'y:Q', alt.value(' '), format=".2f inches")
)

Alternatively, I've tried:

# Draw text labels near the points, and highlight based on selection
y_fld = 'y'
text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, f"{y_fld:.2f} inches", alt.value(' '))
)

I think I see why those don't work, but I can't figure out how to intercept the value of y and pass it through a format string. Thanks!

like image 860
Michael S. Avatar asked Nov 26 '18 15:11

Michael S.


1 Answers

I think the easiest way to do this is to calculate a new field using transform_calculate to compute the label that you want.

Using the example from the documentation, I would change the text chart like this:

text = line.mark_text(align='left', dx=5, dy=-5).encode(
    text=alt.condition(nearest, 'label:N', alt.value(' '))
).transform_calculate(label='datum.y + " inches"')

That leads to this chart: enter image description here

If you want more control, you could change the dataset with pandas beforhand. Be sure to set the type to Nominal (and not Quantitative) otherwise you would get NaNs in the tooltips.

like image 98
FlorianGD Avatar answered Oct 22 '22 03:10

FlorianGD