将文本标签的顺序与堆叠的条形段对齐 [英] Align order of text labels with sorted stacked bar segments

查看:52
本文介绍了将文本标签的顺序与堆叠的条形段对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向此图表添加文本.

I am trying to add text to this chart.

我使用了此代码,文本按正确的顺序,但是其颜色可以根据相应栏的颜色进行更改,因此当我进行bar +文本操作时,文字不可见

I used this code, the text is in its right order but the color of it is changeable according to the color of respective bar so when I bar+text, the text is invisible

人们告诉我这是因为编码中指定的颜色优先于标记属性中指定的颜色" ,因此我应该制作一个没有颜色的基础图,并像这样基于该基础图构建文本:

People told me it is because "Colors specified in encodings take priority over colors specified in mark properties" so I should make a base chart without colors and build text based on that base chart like this:

现在文本为黑色,但显示顺序错误.我认为问题是我只能按颜色订购我的酒吧(先进行带薪工作,然后是教育,睡眠...).因此,如果我不通过在基础图表中为条形着色来使文本变黑,则会失去所需的顺序.

Now the text is black but displayed in wrong order. I think the problem is I only can order my bars as I want (Paid work first, then Education, Sleep...) by colors. So if I want my text black by not coloring my bars in the base chart, I lose the order I want.

有什么办法可以使文本变黑同时保持正确的顺序?(首先是有薪工作,然后是教育,睡眠等).

Is there any way I can make the text black while keeping it in the right order? (Paid work first, then Education, Sleep, so on).

推荐答案

您将需要使用颜色编码来指定排序顺序,并且由于这将覆盖 mark_text 中的所有颜色设置,因此您将还需要将文本颜色编码的范围设置为仅包括黑色.解析色标可确保只有文本被涂成黑色.我认为没有办法在每个条形图中将文本水平居中.

You will need to use the color encoding to specify the sort order and since this will override any color set inside mark_text, you will also need to set the range of the text color encoding to only include black. Resolving the color scale makes sure that only the text is colored black. I don't think there is a way to center the text horizontally within each bar segment.

import altair as alt
from vega_datasets import data

source = data.barley()

site_order = ['Duluth', 'Crookston', 'Waseca', 'University Farm', 'Grand Rapids', 'Morris']
bars = alt.Chart(source).mark_bar().encode(
    x='sum(yield)',
    y='variety',
    color=alt.Color('site', sort=site_order),
    order=alt.Order('color_site_sort_index:Q'))

text = bars.mark_text(align='right', dx=-2).encode(
    x=alt.X('sum(yield):Q', stack=True),
    color=alt.Color('site', sort=site_order, scale=alt.Scale(range=['black']), legend=None),
    text=alt.Text('sum(yield):Q', format='.1f'))

(bars + text).resolve_scale(color='independent')

这篇关于将文本标签的顺序与堆叠的条形段对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆