본문 바로가기

PYTHON

[Python] altair 를 사용한 시각화

안녕하세요. 오랜만에 python 글을 올려봅니다.. ㅎ

 

요즘에 제가 회사에서 시각화를 다루고 있어요.

 

전에 해보지 않았던 터라 좀 어려웠어요ㅜㅜ 그래서 제가 삽질하면서 얻었던 결과를 적어보려고 합니다.

 

특히 altair에 대한 내용은 https://altair-viz.github.io/index.html 이곳에 잘 나와있긴 한데,

 

그래도 직접 해보니까 좀 다르더라구요 ㅎㅎ

 

저도 기억할겸 기록해놓겠습니다!

 

기본적으로 저는 주피터 노트북 환경에서 사용을 했습니다.

 

제가 좀 좋았던 부분은 함수만 변경해주면 bar플롯이나 다른 플롯들로 자동으로 변환되었던 것이었어요.

 

그리고 어려웠던건 결과를 나타내는 일이었는데,

 

제 주피터 환경에서는 결과가 나오지 않더라구요.

그래서 이것 저것 찾아본 결과 html로 저장해서 https://altair-viz.github.io/user_guide/saving_charts.html#html-format

 

Saving Altair Charts — Altair 4.2.0 documentation

If you wish for Altair to take care of the HTML embedding for you, you can save a chart directly to an HTML file using This will create a simple HTML template page that loads Vega, Vega-Lite, and vegaEmbed, such that when opened in a browser the chart will

altair-viz.github.io

결과를 나타내었고, 

# Draw the chart
heatmap + text

# 위와 같던 코드를 아래처럼 바꿔서 
# Draw the chart
(heatmap + text).save('heatmap.html', embed_options={'renderer':'svg'})

이런식으로 저장가능하도록 버튼도 있어서 저장하는 것도 참 편하답니다.

 

그리고 x, y에는 시각화를 원하는 데이터 프레임의 컬럼명을 써주신다고 생각하면 편하구요!

 

title을 넣는 것도 원래 쓰던 plt.plot()요런 애들과 다르게, 

 

import altair as alt
from vega_datasets import data

source = data.cars()

# Configure common options
base = alt.Chart(source).transform_aggregate(
    num_cars='count()',
    groupby=['Origin', 'Cylinders']
).encode(
    alt.X('Cylinders:O', scale=alt.Scale(paddingInner=0)),
    alt.Y('Origin:O', scale=alt.Scale(paddingInner=0)),
).properties(title='타이틀넣기') # 이렇게 properties 안에 넣어줘야해요!

# Configure heatmap
heatmap = base.mark_rect().encode(
    color=alt.Color('num_cars:Q',
        scale=alt.Scale(scheme='viridis'),
        legend=alt.Legend(direction='horizontal')
    )
)

# Configure text
text = base.mark_text(baseline='middle').encode(
    text='num_cars:Q',
    color=alt.condition(
        alt.datum.num_cars > 100,
        alt.value('black'),
        alt.value('white')
    )
)

# Draw the chart
(heatmap + text).save('heatmap.html', embed_options={'renderer':'svg'})

.properties(title='타이틀넣기') 이렇게 properties를 추가해주고 그안에 넣고싶은 타이틀을 넣어주면 끝 !