复合图表¶
Altair 提供简洁的 API 用于创建多面板和叠加图表,我们在这里明确提及其中的三种:
图层叠加
水平连接
垂直连接
重复图表
我们将在这里简要探讨它们。
import altair as alt
图层叠加¶
图层叠加允许您在单个图表上叠加多个标记。一个常见的例子是创建同时包含点和线来表示相同数据的图。
我们使用 stocks
数据作为此示例:
from vega_datasets import data
stocks = data.stocks()
stocks.head()
symbol | date | price | |
---|---|---|---|
0 | MSFT | 2000-01-01 | 39.81 |
1 | MSFT | 2000-02-01 | 36.35 |
2 | MSFT | 2000-03-01 | 43.22 |
3 | MSFT | 2000-04-01 | 28.37 |
4 | MSFT | 2000-05-01 | 25.45 |
这是股票数据的简单折线图:
alt.Chart(stocks).mark_line().encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
这是带有 circle
标记的相同图表:
alt.Chart(stocks).mark_circle().encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
我们可以使用 +
运算符将这两个图叠加在一起:
lines = alt.Chart(stocks).mark_line().encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
points = alt.Chart(stocks).mark_circle().encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
lines + points
这个 +
只是 alt.layer()
函数的快捷方式,它们的作用相同。
alt.layer(lines, points)
我们经常使用的一种模式是创建一个包含公共元素的基础图表,然后叠加两个只进行了一个更改的副本。
base = alt.Chart(stocks).encode(
x='date:T',
y='price:Q',
color='symbol:N'
)
base.mark_line() + base.mark_circle()
水平连接¶
正如我们可以将图表相互叠加一样,我们也可以使用 alt.hconcat
或等效的 |
运算符进行水平连接。
base.mark_line() | base.mark_circle()
alt.hconcat(base.mark_line(),
base.mark_circle())
这对于创建多面板视图非常有用;例如,这是 iris 数据集:
iris = data.iris()
iris.head()
sepalLength | sepalWidth | petalLength | petalWidth | species | |
---|---|---|---|---|---|
0 | 5.1 | 3.5 | 1.4 | 0.2 | setosa |
1 | 4.9 | 3.0 | 1.4 | 0.2 | setosa |
2 | 4.7 | 3.2 | 1.3 | 0.2 | setosa |
3 | 4.6 | 3.1 | 1.5 | 0.2 | setosa |
4 | 5.0 | 3.6 | 1.4 | 0.2 | setosa |
base = alt.Chart(iris).mark_point().encode(
x='petalWidth',
y='petalLength',
color='species'
)
base | base.encode(x='sepalWidth')
重复图表¶
因为水平和垂直连接图表同时只改变一个编码是一种非常常见的模式,Altair 为此提供了一个快捷方式,即使用 repeat()
运算符。
import altair as alt
from vega_datasets import data
iris = data.iris()
fields = ['petalLength', 'petalWidth', 'sepalLength', 'sepalWidth']
alt.Chart(iris).mark_point().encode(
alt.X(alt.repeat("column"), type='quantitative'),
alt.Y(alt.repeat("row"), type='quantitative'),
color='species'
).properties(
width=200,
height=200
).repeat(
row=fields,
column=fields[::-1]
).interactive()
这个 repeat API 目前还没有做到尽善尽美,但我们正在为此努力。