【问题标题】:Altair setting constant label color for bar chartAltair 为条形图设置常量标签颜色
【发布时间】:2019-01-04 11:38:40
【问题描述】:

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

Bar chart with Variable Label Colors

Stacked Bar Chart Example with coloured labels

【问题讨论】:

  • 你好,我不确定我是否理解你想要的正确:设置编码颜色的重点是将变量映射到颜色,这对于变量的所有级别都会有所不同.如果你想要一个恒定的颜色,只需在编码中删除color=... 。这是你想要的还是我错过了什么?
  • 我添加了一个堆积条形图示例来说明问题。我想在堆积条形图中使用“颜色”编码来说明最终达到 100% 的不同组件。在此方案中,从视觉上看,最好使用黑色等单一标签颜色,而不是可能在堆叠条形图中混合和丢失的不同颜色。
  • 如果我理解正确,您想要一个所有颜色都相同的堆积条形图吗? like that 的东西,但所有颜色都一样?

标签: python data-visualization altair


【解决方案1】:

当您执行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') 没有覆盖您的 sn-p 中的编码的原因是因为颜色编码优先于标记属性,如Global Config vs. Local Config vs. Encoding 中所述。

【讨论】:

  • 嗨,杰克,如果我需要在 alt.Chart 规范中保留颜色(用于图例) - 是否还有任何解决方法可以让黑色标记文本
  • 我相信上面答案中的代码可以满足您的需求。
猜你喜欢
  • 2020-08-22
  • 2020-01-21
  • 1970-01-01
  • 2020-03-22
  • 1970-01-01
  • 2019-10-02
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多