官方网站提供了在 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)