Logo
Section 1 / 11

柱状图

学习如何在 Altair 中绘制条形图及其替代方案。

导入

柱状图

学习如何在 Altair 中绘制条形图及其替代方案。

...
柱状图示例
1import altair as alt 2import pandas as pd 3import os 4 5# 加载数据 6df = pd.read_csv("data/sample.csv") 7 8# 创建图表 9chart = alt.Chart(df).mark_bar().encode( 10 x = "Category", 11 y = "Value" 12) 13 14# 显示图表 15chart.save('chart.html') 16os.system('cat chart.html')
...
斜率图
...
哑铃图

按年份划分的水果数量

水果数量年份
橙子102020
苹果32020
西瓜82020
橙子152021
苹果82021
西瓜52021
1import altair as alt 2import pandas as pd 3import os 4 5# 加载数据集 6data = [{'Fruit': 'Orange', 'Quantity' : 10 , 'Year' : 2020}, 7 {'Fruit': 'Apple', 'Quantity' : 3 ,'Year' : 2020}, 8 {'Fruit': 'Watermelon', 'Quantity' : 8 ,'Year' : 2020}, 9 {'Fruit': 'Orange', 'Quantity' : 15 , 'Year' : 2021}, 10 {'Fruit': 'Apple', 'Quantity' : 8 ,'Year' : 2021}, 11 {'Fruit': 'Watermelon', 'Quantity' : 5 ,'Year' : 2021}, 12 ] 13df = pd.DataFrame(data) 14 15# 绘制图表 16colors = ['#1C7E74','#0C9453','#075630'] 17 18chart = alt.Chart(df).mark_bar().encode( 19 y = alt.Y("Quantity"), 20 x = alt.X("Year:O", title='', axis=alt.Axis(labelAngle=0)), 21 column = alt.Column('Fruit', title="各水果在不同年份的数量"), 22 color=alt.Color('Year', legend=None, scale=alt.Scale(range=colors)) 23).properties( 24 width=150 25) 26 27chart.save('chart.html') 28os.system('cat chart.html')
1import altair as alt 2import pandas as pd 3import os 4 5# 加载数据集 6data = [{'Fruit': 'Orange', 'Quantity' : 10 , 'Year' : 2020}, 7 {'Fruit': 'Apple', 'Quantity' : 3 ,'Year' : 2020}, 8 {'Fruit': 'Water Melon', 'Quantity' : 8 ,'Year' : 2020}, 9 {'Fruit': 'Orange', 'Quantity' : 15 , 'Year' : 2021}, 10 {'Fruit': 'Apple', 'Quantity' : 8 ,'Year' : 2021}, 11 {'Fruit': 'Water Melon', 'Quantity' : 5 ,'Year' : 2021}, 12 ] 13df = pd.DataFrame(data) 14 15# 绘制图表 16colors = ['#1C7E74','#0C9453','#075630'] 17 18chart = alt.Chart(df).mark_bar().encode( 19 y = alt.Y("Quantity"), 20 x = alt.X("Fruit:O", title='', axis=alt.Axis(labelAngle=0)), 21 column = 'Year', 22 color=alt.Color('Fruit',legend=None,scale=alt.Scale(range=colors)) 23).properties(width=150) 24 25chart.save('chart.html') 26os.system('cat chart.html')

使用 Altair 进行数据叙事

折线图