Format text of mark_text in Altair

醉酒当歌 提交于 2020-07-05 11:17:48

问题


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!


回答1:


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:

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.



来源:https://stackoverflow.com/questions/53484548/format-text-of-mark-text-in-altair

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!