0

官方网站提供了在 Altair 中为条形图设置标签的示例:https ://altair-viz.github.io/gallery/bar_chart_with_labels.html

但是,一旦您想将条形图中的“颜色”参数设置为以变量为条件,标签颜色会自动匹配条形图的颜色,如下图所示。但是,我的意图是始终保持标签颜色不变,例如黑色。如果要将标签显示为百分比,这对于堆叠条形图尤其有用。似乎在 mark_text 中设置“color='black'”在这里不起作用;可能是因为它基于使用“颜色”参数作为“年份”的“条形图”。但是我找不到一种直观的方法来解耦这个参数。

import altair as alt
from vega_datasets import data

source = data.wheat()

bars = alt.Chart(source).mark_bar().encode(
    x='wheat:Q',
    y="year:O",
    color='year:O'

)

text = bars.mark_text(
    align='left',
    baseline='middle',
        color='black',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='wheat:Q'

)

(bars + text).properties(height=900)

带有可变标签颜色的条形图

带有彩色标签的堆积条形图示例

4

1 回答 1

3

当您执行bars.mark_text()此操作时,生成的图表会继承您在条形图中指定的所有内容,包括颜色编码。为避免对文本进行颜色编码,最好的方法是确保它不继承颜色编码。

例如:

import altair as alt
from vega_datasets import data

source = data.wheat()

base = alt.Chart(source).encode(
    x='wheat:Q',
    y="year:O"
)

bars = base.mark_bar().encode(
    color='year:O'
)

text = base.mark_text(
    align='left',
    baseline='middle',
    dx=3  # Nudges text to right so it doesn't appear on top of the bar
).encode(
    text='wheat:Q'
)

(bars + text).properties(height=900)

之所以mark_text(color='black')没有覆盖代码段中的编码,是因为颜色编码优先于标记属性,如Global Config vs. Local Config vs. Encoding中所述。

于 2019-01-03T21:45:46.680 回答