如何在 Altair 中设置标签文本大小?

How do I set label text size in Altair?

我正在使用 Altair 可视化一些数据,并想在我的图表上添加标签。我以 https://altair-viz.github.io/gallery/scatter_with_labels.html 为例。

我想调整点的大小,但不想调整标签文本的大小。

来自上面的link:

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

这按预期工作。

但是,如果我想改变点的大小以显示更多信息,我会在 points 块中进行调整,现在显示为:

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

不幸的是,我们现在的文本大小也会随着 x 的增加而增加。啊!

text 块中设置 size 命令不会像我期望的那样覆盖文本大小。来自 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 的轴配置建议我得到:ValueError: Objects with "config" attribute cannot be used within LayerChart. Consider defining the config attribute in the LayerChart object instead. 并且不知道下一步该去哪里。

如何在标记大小发生变化时让文本保持相同大小?

当您执行 text = points.mark_text() 时,text 层会继承您在 points 层中定义的所有内容:此处包括 size 编码。

如果您不希望text层有大小编码,您可以只为points层指定它。例如,您可以这样做:

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

mark_text() 块中的设置 size 没有覆盖它的原因是编码总是取代标记属性。有关这方面的更多信息,请参阅 https://altair-viz.github.io/user_guide/customization.html#global-config-vs-local-config-vs-encoding