Altair facet chart 可以有交替的背景颜色吗?
Can an Altair facet chart have alternating background colors?
是否可以在分面图表中设置备用背景颜色?以下尝试将填充设置为标称列会导致全黑背景。
df = pd.DataFrame(data = {'source': ['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']
,'x':[5,4,3,2,1,5,4,3,2,1,5,4,3,2,1]
,'y':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
,'fill':['yes','yes','yes','yes','yes','no','no','no','no','no','yes','yes','yes','yes','yes']})
print(df)
source x y fill
0 a 5 1 yes
1 a 4 2 yes
2 a 3 3 yes
3 a 2 4 yes
4 a 1 5 yes
5 b 5 1 no
6 b 4 2 no
7 b 3 3 no
8 b 2 4 no
9 b 1 5 no
10 c 5 1 yes
11 c 4 2 yes
12 c 3 3 yes
13 c 2 4 yes
14 c 1 5 yes
alt.Chart(df).mark_line().encode(x='x:Q',y='y:Q'
).properties(height=100,width=200
).facet(column='source').configure_view(fill='fill:N')
结果:
期望的结果是这样的交替背景颜色:
不,目前无法在 Altair 的分面图中执行此操作(Vega-Lite 不提供分面背景编码;当您编写 fill='fill:N'
时,渲染器会将 fill:N
解释为不存在的 HTML 颜色的名称)。
如果您想要交替背景,目前唯一的方法是手动连接具有不同背景的图表。
对于手动连接图表,我认为无法将图表与背景或配置对象连接起来。解决方法是在背景图层中手动创建一个矩形标记:
import altair as alt
from vega_datasets import data
source = data.cars()
chart = alt.Chart(source).mark_circle().encode(
x='Horsepower',
y='Miles_per_Gallon',
)
bg = chart.mark_rect(color='coral').encode(
x=alt.value(0),
y=alt.value(0),
x2=alt.value(400),
y2=alt.value(300))
(bg + chart) | (bg.mark_rect(color='gold') + chart)
是否可以在分面图表中设置备用背景颜色?以下尝试将填充设置为标称列会导致全黑背景。
df = pd.DataFrame(data = {'source': ['a','a','a','a','a','b','b','b','b','b','c','c','c','c','c']
,'x':[5,4,3,2,1,5,4,3,2,1,5,4,3,2,1]
,'y':[1,2,3,4,5,1,2,3,4,5,1,2,3,4,5]
,'fill':['yes','yes','yes','yes','yes','no','no','no','no','no','yes','yes','yes','yes','yes']})
print(df)
source x y fill
0 a 5 1 yes
1 a 4 2 yes
2 a 3 3 yes
3 a 2 4 yes
4 a 1 5 yes
5 b 5 1 no
6 b 4 2 no
7 b 3 3 no
8 b 2 4 no
9 b 1 5 no
10 c 5 1 yes
11 c 4 2 yes
12 c 3 3 yes
13 c 2 4 yes
14 c 1 5 yes
alt.Chart(df).mark_line().encode(x='x:Q',y='y:Q'
).properties(height=100,width=200
).facet(column='source').configure_view(fill='fill:N')
结果:
期望的结果是这样的交替背景颜色:
不,目前无法在 Altair 的分面图中执行此操作(Vega-Lite 不提供分面背景编码;当您编写 fill='fill:N'
时,渲染器会将 fill:N
解释为不存在的 HTML 颜色的名称)。
如果您想要交替背景,目前唯一的方法是手动连接具有不同背景的图表。
对于手动连接图表,我认为无法将图表与背景或配置对象连接起来。解决方法是在背景图层中手动创建一个矩形标记:
import altair as alt
from vega_datasets import data
source = data.cars()
chart = alt.Chart(source).mark_circle().encode(
x='Horsepower',
y='Miles_per_Gallon',
)
bg = chart.mark_rect(color='coral').encode(
x=alt.value(0),
y=alt.value(0),
x2=alt.value(400),
y2=alt.value(300))
(bg + chart) | (bg.mark_rect(color='gold') + chart)