python - 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
解决方案
有两种方法可以做到这一点; 未记录且将来可能无法使用的快速方法,以及更多代码的更健壮的方法。
快速方法依赖于使用 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
)
)
推荐阅读
- javascript - 为什么 Visual Studio Code 没有突出显示“this.***”未使用的变量?
- python - kivy按钮调用另一个类的方法
- python - Amazon WS S3:我收到此错误消息:“您尝试访问的存储桶必须使用指定的终端节点进行寻址。”
- r - R - 闪亮的应用程序 - 错误:无效的 git repo 规范:'ShinySky'
- sql-server - TSQL 取消长时间运行的 UPDATE 而不回滚
- sql - 在 SQL 数据库上训练决策树分类器
- html - Divs All Visible at Page opening(尽管有 jquery,在单选按钮单击时显示 div)
- php - 漂亮的 url 静态文件未加载
- python - 错误纠正的第一个代码澄清?
- node.js - VueJS axios.get 返回错误:请求失败,状态码 404