[英]Altair setting constant label color for bar chart
在以下官方网站中提供了在Altair中设置条形图标签的示例: https : //altair-viz.github.io/gallery/bar_chart_with_labels.html
但是,一旦您想在条形图中将“ color”参数设置为一个变量,标签颜色就会自动匹配条形的颜色,如下所示。 但是,我的目的是使标签颜色始终保持不变,就像一直保持黑色。 如果要将标签显示为百分比,则这对于堆叠条形图尤其理想。 在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)
当您执行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中所述,颜色编码优先于标记属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.