堪比 Excel,Python 可视化神器 Altair 入门详解
数据转化成更直观的图片,对于理解数据背后的真相很有帮助。如果你有这方面的需求,而且还在使用Python,那么强烈推荐你试一试Altair。
Altair是一个专为Python编写的可视化软件包,它能让数据科学家更多地关注数据本身和其内在的联系。 Altair由华盛顿大学的数据科学家Jake Vanderplas编写,目前在GitHub上已经收获超过3000星。 最近,Medium上一位小姐姐Parul Pandey分享了Altair的入门教程,希望对从事数据科学的用户有帮助。量子位对主要内容进行了编译整理。使用教程
Parul以汽车数据为例,将一个汽车数据集“cars”载入到Altair中。 cars中包含汽车的生产年份、耗油量、原产国等9个方面的数据,后面将对这些内容进行可视化处理。安装和导入Altair软件包
除了安装Altair和它的依赖软件外,还需要安装其他前端工具,比如Jupyter Notebook、JupyterLab、Colab等等。 Parul小姐姐推荐安装JupyterLab: $ pip install -U altair vega_datasets jupyterlab 需要注意的是,由于Altair的教程文档中还包含vega数据集,因此也需要一并安装上。 接着在终端中输入:jupyter lab,就能在你的浏览器中自动打开它啦。 在代码开头别忘了导入Altair:import altair as alt
开始绘制图表
Altair中的基本对象是Chart,它将数据框作为单个参数。你可以这样定义它:chart = alt.Chart(cars)
alt.Chart(data).mark_point().encode(
encoding_1="column_1"
,encoding_2="column_2",
# etc.
)
alt.Chart(cars).mark_point().encode(
x="Miles_per_Gallon"
)
alt.Chart(cars).mark_tick().encode(
x="Miles_per_Gallon"
)
alt.Chart(cars).mark_line().encode(
x="Miles_per_Gallon",
y="Horsepower"
)
给图表上色
前面我们已经学会了绘制二维图像,如果能给不同组的数据分配不同的颜色,就相当于给数据增加了第三个维度。alt.Chart(cars).mark_point().encode(
x="Miles_per_Gallon",
y="Horsepower",
color="Origin"
)
alt.Chart(cars).mark_point().encode(
x="Miles_per_Gallon",
y="Horsepower",
color="Acceleration"
)
数据的分类与汇总
上面的例子中,我们使用的主要是散点图。实际上,Altair还能方便地对数据进行分类和汇总,绘制统计直方图。 相比其他绘图工具,Altair的特点在于不需要调用其他函数,而是直接在数轴上进行修改。 例如统计不同油耗区间的汽车数量,对X轴使用alt.X(),指定数据和间隔大小,对Y轴使用count()统计数量。alt.Chart(cars).mark_bar().encode(
x=alt.X("Miles_per_Gallon", bin=alt.Bin(maxbins=30)),
y="count()"
)
alt.Chart(cars).mark_bar().encode(
x=alt.X("Miles_per_Gallon",bin=alt.Bin(maxbins=30)),
y="count()",
color="Origin"
)
alt.Chart(cars).mark_bar().encode(
x=alt.X("Miles_per_Gallon",bin=alt.Bin(maxbins=30)),
y="count()",
color="Origin",
column="Origin"
)
交互
除了绘制基本图像,Altair强大之处在于用户可以与图像进行交互,包括平移、缩放、选中某一块数据等操作。 在绘制图片的代码后面,调用interactive()模块,就能实现平移、缩放: Altair还为创建交互式图像提供了一个selection的API: 在选择功能上,我们能做出一些更酷炫的高级功能,例如对选中的数据点进行统计,生成实时的直方图。叠加多个图层
如果把前面的汽车耗油量按年度计算出平均值:alt.Chart(cars).mark_point().encode(
x="Miles_per_Gallon",
y="Horsepower",
color="Acceleration"
)
alt.Chart(cars).mark_area(opacity=0.3).encode(
x=alt.X(‘Year’, timeUnit=’year’),
y=alt.Y(‘ci0(Miles_per_Gallon)’,axis=alt.Axis(title=’Miles per Gallon’)),
y2=’ci1(Miles_per_Gallon)’,
color=’Origin’
).properties(
width=600
)
spread = alt.Chart(cars).mark_area(opacity=0.3).encode(
x=alt.X("Year", timeUnit="year"),
y=alt.Y("ci0(Miles_per_Gallon)", axis=alt.Axis(title="Miles per Gallon")),
y2="ci1(Miles_per_Gallon)",
color="Origin"
).properties(
width=800
)
lines = alt.Chart(cars).mark_line().encode(
x=alt.X("Year", timeUnit="year"),
y="mean(Miles_per_Gallon)",
color="Origin"
).properties(
width=800
)
spread + lines