3

I'm visualizing some data with Altair, and want to put labels on my chart. I've used https://altair-viz.github.io/gallery/scatter_with_labels.html as an example.

I want to adjust the size of my points but not the size of the label text.

From the link above:

import altair as alt
import pandas as pd

source = pd.DataFrame({
    'x': [1, 3, 5, 7, 9],
    'y': [1, 3, 5, 7, 9],
    'label': ['A', 'B', 'C', 'D', 'E']
})

points = alt.Chart(source).mark_point().encode(
    x='x:Q',
    y='y:Q'
)

text = points.mark_text(
    align='left',
    baseline='middle',
    dx=7
).encode(
    text='label'
)

points + text

This works as expected.

However, if I want to vary the size of my points to show additional information, in the points block I adjust so it now reads:

x='x:Q',
y='y:Q'
size='x'
)

Unfortunately we now also have text size that increases with x. Argh!

Setting a size command inside the text block doesn't override the text size as I expect it to. The axis configuration suggestions from How do you set Axis FontSize in Altair? have not solved my problem. If I use configure_text from https://altair-viz.github.io/user_guide/generated/toplevel/altair.Chart.html#altair.Chart.configure_text I get: ValueError: Objects with "config" attribute cannot be used within LayerChart. Consider defining the config attribute in the LayerChart object instead. and don't know where to go next.

How can I get the text to stay the same size while the mark size changes?

vtnate
  • 133
  • 1
  • 9

1 Answers1

5

When you do text = points.mark_text(), the text layr inherits everything you defined in the points layer: here, that includes the size encoding.

If you do not want the text layer to have a size encoding, you can specify it only for the points layer. For example, you could do something like this:

points = alt.Chart(source).mark_point().encode(
    x='x:Q',
    y='y:Q',
    size='x'
)

text = alt.Chart(source).mark_text(
    align='left',
    baseline='middle',
    dx=7
).encode(
    x='x:Q',
    y='y:Q',
    text='label'
)

points + text

The reason setting size in the mark_text() block doesn't override this is because encodings always supersede mark properties. See https://altair-viz.github.io/user_guide/customization.html#global-config-vs-local-config-vs-encoding for more information on this.

jakevdp
  • 77,104
  • 11
  • 125
  • 160
  • 1
    That worked, thank you! I get that `text` inherits from `points`; I am surprised that it isn't overwritten by new values to the same variable. – vtnate Aug 19 '19 at 16:59
  • 2
    See my edit at the bottom with more information on this. – jakevdp Aug 19 '19 at 16:59