简体   繁体   中英

How do I set label text size in Altair?

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. 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM