问题描述
这是我之前关于 altair Ridgeline 情节的 question 扩展。
import pandas as np
import numpy as np
source = pd.DataFrame(columns=list('ab'))
source['a'] = np.random.randint(0,17,size=500)
source['color'] = source['a'].apply(lambda x: 'blue' if x < 10 else 'red']
source['a'] = source['a'].astype('str')
source['b'] = np.random.randint(1000,5000,size=500).astype('float')
import altair as alt
step = 20
overlap = 1
alt.Chart(source,height=step).transform_joinaggregate(
mean_temp='mean(b)',groupby=['a']
).transform_bin(
['bin_max','bin_min'],'b'
).transform_aggregate(
value='count()',groupby=['a','b','bin_min','bin_max']
).transform_impute(
impute='value','b'],key='bin_min',value=0
).mark_area(
interpolate='monotone',fillOpacity=0.8,stroke='lightgray',strokeWidth=0.5
).encode(
alt.X('bin_min:Q',bin='binned',title=''),alt.Y(
'value:Q',scale=alt.Scale(range=[step,-step * overlap]),axis=None
),alt.Fill(
'b:Q',legend=None,)
).facet(
row=alt.Row(
'a:N',title=None,header=alt.Header(labelAngle=0,labelAlign='right')
)
).properties(
title='',bounds='flush'
).configure_facet(
spacing=0
).configure_view(
stroke=None
).configure_title(
anchor='end'
)
我的问题是如何使绘图的行具有不同的颜色(“蓝色”或“红色”取决于数据框中的“颜色”列)?我尝试使用 alt.Scale(domain='color:N')
中的 alt.Fill()
、color='color:N'
中的 encode()
参数对其进行配置,但它不起作用。构面标题标签也应着色。
解决方法
您可以通过将填充或颜色编码设置为带有 raw scale 的 "color"
列来实现。
也就是说,您已经根据 "b"
列设置了颜色编码,因此您需要对这些信息进行不同的编码;例如,您可以改用 Opacity。
以下是将这些组合在一起的示例:
import pandas as np
import numpy as np
source = pd.DataFrame(columns=list('ab'))
source['a'] = np.random.randint(0,17,size=500)
source['color'] = source['a'].apply(lambda x: 'blue' if x < 10 else 'red')
source['a'] = source['a'].astype('str')
source['b'] = np.random.randint(1000,5000,size=500).astype('float')
import altair as alt
step = 20
overlap = 1
alt.Chart(source,height=step).transform_joinaggregate(
mean_temp='mean(b)',groupby=['a']
).transform_bin(
['bin_max','bin_min'],'b'
).transform_aggregate(
value='count()',groupby=['a','b','bin_min','bin_max','color']
).transform_impute(
impute='value','color'],key='bin_min',value=0
).mark_area(
interpolate='monotone',fillOpacity=0.8,stroke='lightgray',strokeWidth=0.5
).encode(
alt.X('bin_min:Q',bin='binned',title=''),alt.Y(
'value:Q',scale=alt.Scale(range=[step,-step * overlap]),axis=None
),alt.Fill('color:N',scale=None),alt.Opacity(
'b:Q',legend=None,)
).facet(
row=alt.Row(
'a:N',title=None,header=alt.Header(labelAngle=0,labelAlign='right')
)
).properties(
title='',bounds='flush'
).configure_facet(
spacing=0
).configure_view(
stroke=None
).configure_title(
anchor='end'
)