- import
import altair as alt
import pandas as pd
- alt.Chart(data).mark_bar().encode() 바 그래프
source = pd.DataFrame({
'a': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I'],
'b': [28, 55, 43, 91, 81, 53, 19, 87, 52]
})
alt.Chart(source).mark_bar().encode(
x='a',
y='b'
)
# y = "count()"로 하면 히스토그램이 됨
- alt.Chart(data).mark_point().encode() 스캐터
import altair as alt
# Import data object from vega_datasets
from vega_datasets import data
# Selecting the data
iris = data.iris()
# Making the Scatter Plot
alt.Chart(iris).mark_point().encode(
# Map the sepalLength to x-axis
x='sepalLength',
# Map the petalLength to y-axis
y='petalLength',
# Map the species to shape
shape='species'
color='Origin'
)
- alt.Chart(data).mark_line().encode() 선
import numpy as np
x = np.arange(100)
data = pd.DataFrame({"x": x, "sin(x)": np.sin(x / 5)})
alt.Chart(data).mark_line().encode(x="x", y="sin(x)")
# alt.Chart(data).mark_line(point= True).encode(x="x", y="sin(x)") 수행하면 점선 같이
- heatmap
# Compute x^2 + y^2 across a 2D grid
x, y = np.meshgrid(range(-5, 5), range(-5, 5))
z = x**2 + y**2
# Convert this grid to columnar data expected by Altair
data = pd.DataFrame({"x": x.ravel(), "y": y.ravel(), "z": z.ravel()})
alt.Chart(data).mark_rect().encode(x="x:O", y="y:O", color="z:Q")
- alt.Chart(iowa).mark_area().encode() 면적 그리기
import altair as alt
from vega_datasets import data
iowa = data.iowa_electricity()
alt.Chart(iowa).mark_area().encode(x="year:T", y="net_generation:Q", color="source:N")
- 수평으로 두개의 서브 플롯
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
# | 로 합침
-수직으로 두개의 서브플롯 만들기
import altair as alt
from vega_datasets import data
source = data.sp500.url
brush = alt.selection(type='interval', encodings=['x'])
base = alt.Chart(source).mark_area().encode(
x = 'date:T',
y = 'price:Q'
).properties(
width=600,
height=200
)
upper = base.encode(
alt.X('date:T', scale=alt.Scale(domain=brush))
)
lower = base.properties(
height=60
).add_selection(brush)
alt.vconcat(upper, lower)
# vconcat으로 합침
- 2x2 subplot
import altair as alt
from vega_datasets import data
iris = data.iris.url
alt.Chart(iris).mark_point().encode(
alt.X(alt.repeat("column"), type='quantitative'),
alt.Y(alt.repeat("row"), type='quantitative'),
color='species:N'
).properties(
width=200,
height=200
).repeat(
row=['petalLength', 'petalWidth'],
column=['sepalLength', 'sepalWidth']
).interactive()
참고코드
11.Bokeh & Altair -2.ipynb
0.48MB