首页 > 解决方案 > Altair 颜色分级值

问题描述

在以下直方图中着色分箱值时遇到问题。我打算对 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

在此处输入图像描述

标签: pythondata-visualizationaltair

解决方案


有两种方法可以做到这一点; 未记录且将来可能无法使用的快速方法,以及更多代码的更健壮的方法。

快速方法依赖于使用 vega 生成的内部字段名称进行分箱编码:

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
    )
)

在此处输入图像描述

记录的方法是将您的分箱从编码移动到显式转换,这有点冗长:

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
    )
)

在此处输入图像描述


推荐阅读