tko*_*leh 4 python data-visualization 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
Run Code Online (Sandbox Code Playgroud)
有两种方法可以做到这一点; 快速的方法没有记录,将来可能行不通,而更健壮的方法是需要更多的代码。
快速方法依赖于使用 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
)
)
Run Code Online (Sandbox Code Playgroud)
记录的方法是将分箱从编码移至显式转换,这有点冗长:
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
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1336 次 |
| 最近记录: |