Altair颜色分箱值

4

在以下直方图中,对于已分箱值的柱状,我遇到了着色问题。我想要将所有在 x 轴(信用)上小于 50 的柱子着色。如何在 Altair 中实现?

base = alt.Chart(X_train)

histogram = base.mark_bar().encode(
    alt.X('Creditworthiness', bin=True),
    y='count()',
    color=alt.condition(
        alt.datum.Creditworthiness < 50,
        alt.value("steelblue"),  # The positive color
        alt.value("orange")  # The negative color
    )
)

threshold_line = pd.DataFrame([{"threshold": max_profit_threshold}])
mark = alt.Chart(threshold_line).mark_rule(color="#e45755").encode(
    x='threshold:Q',
    size=alt.value(2)
)

histogram + mark

enter image description here

2个回答

7

有两种方法可以做到这一点;快速的方式是未记录的,将来可能无法使用,而更健壮的方式需要编写更多的代码。

快速的方式依赖于使用由vega为binned编码生成的内部字段名称:

import altair as alt
import pandas as pd
import numpy as np

np.random.seed(1701)
X_train = pd.DataFrame({
    'Creditworthiness': np.clip(50 + 20 * np.random.randn(300), 0, 100)
})

alt.Chart(X_train).mark_bar().encode(
    alt.X('Creditworthiness', bin=True),
    y='count()',
    color=alt.condition(
        alt.datum.bin_maxbins_10_Creditworthiness_end <= 50,
        alt.value("steelblue"),  # The positive color
        alt.value("orange")  # The negative color
    )
)

enter image description here

文档推荐的方法是将您的分组从编码中移动到显式转换中,这会更加冗长:

alt.Chart(X_train).transform_bin(
    'Creditworthiness_bin', 'Creditworthiness', bin=alt.Bin(step=10)
).transform_joinaggregate(
    count='count()', groupby=['Creditworthiness_bin']  
).mark_bar(orient='vertical').encode(
    alt.X('Creditworthiness_bin:Q', bin='binned'),
    alt.X2('Creditworthiness_bin_end'),
    alt.Y('count:Q'),
    color=alt.condition(
        alt.datum.Creditworthiness_bin_end <= 50,
        alt.value("steelblue"),  # The positive color
        alt.value("orange")  # The negative color
    )
)

enter image description here


感谢分享这两种方法。我想给X轴上小于50的条形图染色。我已经进一步澄清了问题。对于混淆造成的困扰,我表示歉意。目标是突出显示低于阈值的申请人数。 - tkolleh
1
我猜这个问题的核心是如何知道轴名称将如何被解释,以便通过 alt.datum.* 访问它。例如,特殊字符如何处理,大小写是否敏感等等... - tkolleh
bin_maxbins_10_Creditworthiness_end 这个名称是从哪里来的? - PaleNeutron

2
这是一种既简洁又健壮的方法,使用了Altair文档中记录的参数。它通过对颜色编码进行分组(使用给定的阈值作为分组步骤),同时限制颜色比例尺(颜色来自“category10”分类颜色方案)。请保留HTML标签。
import altair as alt
import pandas as pd
import numpy as np

np.random.seed(1701)
X_train = pd.DataFrame({
    'Creditworthiness': np.clip(50 + 20 * np.random.randn(300), 0, 100)
})
threshold = 50

alt.Chart(X_train).mark_bar().encode(
    alt.X('Creditworthiness', bin=True),
    y='count()',
    color=alt.Color('Creditworthiness', bin=alt.Bin(step=threshold), scale=alt.Scale(domain=[0, threshold], range=["#1f77b4", "#ff7f0e"]), legend=None),
)

Binned histogram of credit worthiness (blue below threshold of 50, and orange above)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接