8

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!

Michael S.
  • 327
  • 1
  • 2
  • 11

1 Answers1

11

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.

ijoseph
  • 6,505
  • 4
  • 26
  • 26
FlorianGD
  • 2,336
  • 1
  • 15
  • 32
  • 8
    Thanks! I wasn't quite sure what datum was but it seems to be an altair convention. I also wanted to round the values which I was able to do as follows, for anyone else slightly confused: `.transform_calculate(label=f'format(datum.{fld},".1f") + " inches"')` – Michael S. Nov 27 '18 at 03:22
  • datum is vega's way to access data. There is more information in the documentation https://altair-viz.github.io/user_guide/transform.html Good job on formatting your data! – FlorianGD Nov 27 '18 at 11:14