如何修改Vega-Lite饼图内部文本标签的颜色
Vega-Lite环形饼图内部标签颜色修改方案
问题原因
你代码中的color编码配置在全局顶层,该规则会自动对layer下的所有图层生效,因此文本标签会继承对应扇区的颜色,放在扇区内部时就会因为同色无法显示。
修复方法
你只需要在文本图层的mark配置中,手动指定固定的color属性覆盖全局继承的颜色即可,需要黑色就填"black",需要白色就填"white":
// 仅需修改文本层的mark配置 { mark: {type: "text", radius: 70, color: "white"}, encoding: {text: {field: "occurances", type: "quantitative"}} }
完整修改后JS代码
vegaEmbed("#graph", { $schema: "https://vega.github.io/schema/vega-lite/v5.json", data: { values: [ {event: "a", occurances: 28}, {event: "b", occurances: 3}, {event: "c", occurances: 1}, {event: "d", occurances: 3}, {event: "e", occurances: 1}, {event: "f", occurances: 10}, {event: "g", occurances: 2}, {event: "h", occurances: 1}, {event: "k", occurances: 1} ] }, layer: [ {mark: {type: "arc", innerRadius: 50, outerRadius: 100}}, { mark: {type: "text", radius: 70, color: "white"}, encoding: {text: {field: "occurances", type: "quantitative"}} } ], encoding: { color: {field: "event", type: "nominal"}, theta: {field: "occurances", type: "quantitative", stack: true} } });
注:已修正原代码中quantitive的拼写错误为quantitative
可选进阶:自动适配黑白标签
如果需要文本颜色根据扇区背景深浅自动切换(亮色背景用黑字、暗色背景用白字),可以给文本层添加颜色条件编码,基于扇区颜色的亮度自动判断输出文字颜色。
内容的提问来源于stack exchange,提问作者Noam I.
相关产品推荐
相关产品推荐

