- This article shares another python interactive visualization tool Altair . The bottom layer of Altair is Vega-Lite (based on a simple interactive visualization grammar, A Grammar of Interactive Graphics), with effects such as:
- The author of Altair is Jake Vanderplas. He is a big man. He was previously the Dean of the Institute of Physics of the University of Washington eScience School. He is now a Software Engineer at Google. He is passionate about Python, Astronomy and Data Science. He is also an active open source enthusiast. He can see his talk at PyData conferences over the years. In addition to Altair, he has made a lot of contributions to famous Python libraries such as Scikit-Learn, Scipy, Matplotlib, IPython, etc.; author of two high-star books Python Data Science Handbook and A Whirlwind Tour of Python.
table of Contents
1. Quick start of Altair basic graphics
Python's Altair script is converted to JSON
2. Quick start of Altair complex graphics
configure_*() methods to personalize image attributes
Selection, condition, and binding make altair graphics better interact with the mouse
Layer, HConcat, VConcat, Repeat, Facet help altair easily build composite graphics
3. Demo sharing based on Altair
A case on the official website about the weather
Official website: https://altair-viz.github.io/index.html
1. Quick start of Altair basic graphics
This summary introduces how to quickly draw common basic graphs , such as “bar”, “circle”, “square”, “tick”, “line”, * “area”, “point”, “rule”, “geoshape”, and "text" etc.
pip install altair
pip install altair vega_datasets -i https://pypi.tuna.tsinghua.edu.cn/simple#国内源加速安装
Altair drawing step by step
-
data preparation
The iris iris data set is still used. For the introduction of the data set, see: Python visualization|matplotlib10-drawing scatter plots
import seaborn as sns
pd_iris = sns.load_dataset("iris")
pd_iris.head(n=5)
-
Quick drawing
#快速绘图
import altair as alt
import pandas as pd
alt.Chart(pd_iris).mark_point().encode(x='sepal_length',
y='sepal_width',
color='species')
-
Drawing step split
From the code of alt. Chart (pd_iris). mark_ point(). encode (x='sepal_length',y='sepal_width',color='species'), we can see that Altair drawing mainly uses the Chart() method and mark_* () method, and encode() method.
The Chart() method converts the data into an altair.vegalite.v4.api.Chart object
The height, width, background color, etc. of the image can be set in the brackets. For details, see: https://altair-viz.github.io/user_guide/generated/toplevel/altair.Chart.html?highlight=chart
The mark_*() method specifies the graphics to be displayed, such as drawing a scatter chart mark_point()
The mark_*() method sets graphic attributes, such as color, size, etc.
Various attributes of the graphics to be displayed can be set in the brackets. Take mark_point() to set the point color as an example as follows.
For other detailed parameters, see: https://altair-viz.github.io/user_guide/generated/toplevel/altair.Chart.html?highlight=mark_point#altair.Chart.mark_point
The encode() method sets the mapping of the coordinate axis
Detailed parameters: https://altair-viz.github.io/user_guide/generated/toplevel/altair.Chart.html?highlight=encode#altair.Chart.encode
Python's Altair script is converted to JSON
python script
import altair as alt
import pandas as pd
data = pd.DataFrame({'x': ['A', 'B', 'C', 'D'], 'y': [1, 2, 1, 2]})
alt.Chart(data).mark_bar().encode(
x='x',
y='y',
)
Click to get the json script
{
"config": {"view": {"continuousWidth": 400, "continuousHeight": 300}},
"data": {"name": "data-39e740acccd9d827d4364cdbd6d37176"},
"mark": "bar",
"encoding": {
"x": {"type": "nominal", "field": "x"},
"y": {"type": "quantitative", "field": "y"}
},
"$schema": "https://vega.github.io/schema/vega-lite/v4.8.1.json",
"datasets": {
"data-39e740acccd9d827d4364cdbd6d37176": [
{"x": "A", "y": 1},
{"x": "B", "y": 2},
{"x": "C", "y": 1},
{"x": "D", "y": 2}
]
}
}
2. Quick start of Altair complex graphics
This section briefly introduces more complex graphics, such as personalized facet diagram titles, legends, configure_*() methods , selection() binding_*() methods ,方法、condition()方法、
configure_*() methods to personalize image attributes
The configure_header() method personalizes the header
import altair as alt
from vega_datasets import data#vega_datasets为altair的一个内置数据集模块
source = data.cars.url
chart = alt.Chart(source).mark_point().encode(x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color='Origin:N',
column='Origin:N').properties(
width=180, height=180)
chart.configure_header(titleColor='green',
titleFontSize=14,
labelColor='red',
labelFontSize=14)
Personalize the legend of the configure_legend() method
import altair as alt
from vega_datasets import data
source = data.cars.url
chart = alt.Chart(source).mark_point().encode(x='Horsepower:Q',
y='Miles_per_Gallon:Q',
color='Origin:N')
chart.configure_legend(strokeColor='gray',
fillColor='#EEEEEE',
padding=10,
cornerRadius=10,
orient='top-right')
For more configure method introduction, please see: https://altair-viz.github.io/user_guide/configuration.html
Selection, condition, and binding make altair graphics better interact with the mouse
The selection(), condition(), and binding() methods are mainly used here , a brief introduction, see for details: https://altair-viz.github.io/user_guide/interactions.html
-
selection() method
The mouse can lightly capture a certain part of the graph.
-
condition() method
Make the part captured by the mouse brighten, and the part that is not captured is dimmed.
-
binding_*() method
The effect is as follows:
Layer, HConcat, VConcat, Repeat, Facet help altair easily build composite graphics
-
hconcat水平方向拼图
import altair as alt
from vega_datasets import data
iris = data.iris.url
chart1 = alt.Chart(iris).mark_point().encode(x='petalLength:Q',
y='petalWidth:Q',
color='species:N').properties(
height=300, width=300)
chart2 = alt.Chart(iris).mark_bar().encode(x='count()',
y=alt.Y('petalWidth:Q',
bin=alt.Bin(maxbins=30)),
color='species:N').properties(
height=300, width=100)
chart1 | chart2
alt.hconcat(chart1, chart2)
-
vconcat vertical puzzle
-
LayerChart图层叠加
-
RepeatChart draws similar graphics
from vega_datasets import data
iris = data.iris.url
base = alt.Chart().mark_point().encode(color='species:N').properties(
width=200, height=200).interactive()
chart = alt.vconcat(data=iris)
for y_encoding in ['petalLength:Q', 'petalWidth:Q']:
row = alt.hconcat()
for x_encoding in ['sepalLength:Q', 'sepalWidth:Q']:
row |= base.encode(x=x_encoding, y=y_encoding)
chart &= row
chart
-
FacetChart graphics facet
import altair as alt
from altair.expr import datum
from vega_datasets import data
iris = data.iris.url
base = alt.Chart(iris).mark_point().encode(x='petalLength:Q',
y='petalWidth:Q',
color='species:N').properties(
width=160, height=160)
chart = alt.hconcat()
for species in ['setosa', 'versicolor', 'virginica']:
chart |= base.transform_filter(datum.species == species)
chart
Chart.resolve_scale(), Chart.resolve_axis(), and Chart.resolve_legend() personalized composite graphics
For example, use resolve_scale() to use color wheels for two graphs respectively.
from vega_datasets import data
source = data.cars()
base = alt.Chart(source).mark_point().encode(
x='Horsepower:Q', y='Miles_per_Gallon:Q').properties(width=200, height=200)
alt.concat(base.encode(color='Origin:N'),
base.encode(color='Cylinders:O')).resolve_scale(color='independent')
3. Demo sharing based on Altair
A case of official gateway and weather
from vega_datasets import data
df = data.seattle_weather()
scale = alt.Scale(
domain=['sun', 'fog', 'drizzle', 'rain', 'snow'],
range=['#e7ba52', '#c7c7c7', '#aec7e8', '#1f77b4', '#9467bd'])
brush = alt.selection(type='interval')
points = alt.Chart().mark_point().encode(
alt.X('temp_max:Q', title='Maximum Daily Temperature (C)'),
alt.Y('temp_range:Q', title='Daily Temperature Range (C)'),
color=alt.condition(brush,
'weather:N',
alt.value('lightgray'),
scale=scale),
size=alt.Size('precipitation:Q',
scale=alt.Scale(range=[1, 200]))).transform_calculate(
"temp_range",
"datum.temp_max - datum.temp_min").properties(
width=600, height=400).add_selection(brush)
bars = alt.Chart().mark_bar().encode(
x='count()',
y='weather:N',
color=alt.Color('weather:N', scale=scale),
).transform_calculate(
"temp_range",
"datum.temp_max - datum.temp_min").transform_filter(brush).properties(
width=600)
alt.vconcat(points, bars, data=df)
For other cases, please refer to the official website, no more handling:
Official website: https://altair-viz.github.io/index.html
-
Simple graph
-
bar graph
-
line graph
-
area graph
-
scatter diagram
-
histgogram chart
-
map
-
Interactive diagram
-
Case Studies
-
Other Charts