Altair 是一款声明式统计可视化库,以其强大而简洁的可视化语法著称,可以帮助你快速构建各种可视化效果。
https://github.com/altair-viz/altair
优势在于其 API 特性,可以与 pandas dataframe 集成,使你能更好地理解数据。Altair 可用于创建多种美观的图表,如条形图、饼图、直方图、散点图等。
初体验
库的安装
你可以使用以下命令之一进行安装:
<code>pip install altair</code>
或者:
<code>conda install altair -c conda-forge</code>
示例
今天,我们将学习如何使用 Altair 创建交互式散点图。交互式绘图可以提供比标准绘图更多的信息,并增加了可视化的灵活性。我们将使用的数据集来自 。
http://insideairbnb.com/get-the-data/
首先,我们需要对数据进行处理。价格列以对象数据类型存储,我们需要将其转换为数字格式:
<code>df.loc[:, "price"] = df.loc[:, "price"].str[1:].str.replace(",","").astype("float") df = df[df["price"] < 1000]</code>
散点图
散点图通常用于可视化两个连续变量之间的关系。我们可以创建散点图来检查“住宿”列和“价格”列之间的关系。
<code>alt.Chart(df).mark_circle(size=50).encode( alt.X("accommodates"), alt.Y("price"), alt.Color("room_type", legend=alt.Legend( title="Room Type", orient='left', titleFontSize=15, labelFontSize=13) ) ).properties( height=350, width=500 ).configure_axis( titleFontSize=20, labelFontSize=15 )</code>
交互功能
交互功能允许放大和缩小绘图。我们可以通过添加 size 属性来增强前面示例中的绘图:
<code>alt.Chart(df.sample(100)).mark_circle(size=50).encode( alt.X("accommodates"), alt.Y("reviews_per_month"), alt.Color("room_type", legend=alt.Legend( title="Room Type", orient='left', titleFontSize=15, labelFontSize=13) ), alt.Size("price", legend=alt.Legend( title="Price", orient='left', titleFontSize=15, labelFontSize=13)) ).properties( height=350, width=500 ).configure_axis( titleFontSize=20, labelFontSize=15 ).interactive()</code>
互动图例
交互性也可用于制作更多信息和功能的绘图。例如,我们可以通过将图例用作过滤器来增强交互性:
<code>selection = alt.selection_multi(fields=['room_type'], bind='legend') alt.Chart(df).mark_circle(size=50).encode( alt.X("accommodates"), alt.Y("price"), alt.Color("room_type", legend=alt.Legend( title="Room Type", orient='left', titleFontSize=15, labelFontSize=13) ), opacity=alt.condition(selection, alt.value(1), alt.value(0)) ).properties( height=350, width=500 ).configure_axis( titleFontSize=20, labelFontSize=15 ).add_selection( selection )</code>
Altair 在交互组件方面还有更多功能。一旦你了解了交互性的概念(例如选择、绑定和条件),你就可以创建令人惊叹的数据可视化效果。
© 版权声明
THE END
暂无评论内容