IT 프로그래밍/AI

Bokeh를 이용한 대화형 웹 시각화

기술1 2024. 9. 8. 17:56

설치 및 output

!pip install bokeh
import numpy as np
from bokeh.io import output_notebook, show
from bokeh.plotting import figure

output_notebook()

해당 코드는 colab을 통해 이용했습니다. output 기능을 이용해 바로 출력할 수 있도록 해주었습니다.

 

p = figure(width=400, height=400)

show(p)

이렇게 크기를 설정해줍니다.

 

x = [0,1,2,3,4,5]
y = [0,1,2,3,4,5]
p.circle(x, y, size=10)
show(p)

이후 예시 하나로 x와 y를 잡고서 이거에 대한 p.circle을 그린 그래프를 보겠습니다.

보면 (0,0)에 1번째, (1,1)에 2번째.. 이렇게 출력이 된 것을 볼 수 있습니다. 이거에 대한 색깔을 입히고 싶다거나 조절을 하고 싶은 부분은 코드에서 작업해주시면 됩니다.

 

p.circle(x, y, size=10, line_color ='orange', fill_color='red')
show(p)

이렇게 색깔을 변경해줄 수도 있습니다.

 

이런 것은 외워야 하는 것은 아닙니다. 이렇게 적용할 수 있다라는 것을 인지만 하시고 중에 프로그래밍 작업을 할 때 쓸 수 있도록 감을 익히시면 됩니다.

 

p.circle(x, y, size=10, line_color ='orange', fill_color='red', fill_alpha =0.2)
show(p)

이렇게 fill_alpha를 통해 투명도를 작업해줄 수도 있습니다. 

 

웹에 필요한 시각화 코드 분석

import bokeh
bokeh.sampledata.download()

 

먼저 bokeh를 다운로드해줍니다.

 

import pandas as pd
from bokeh.plotting import figure
from bokeh.sampledata.stocks import AAPL

df = pd.DataFrame(AAPL)
df

이번에 예시 데이터는 주식에 관련된 AAPL입니다. AAPL을 불러온 다음에 df으로 해당 AAPL을 잡아줍니다. 

그러면 해당 데이터셋이 나오게 됩니다. 총 3270 rows * 7 columns입니다. 

 

pd.to_datetime(df['date'])

이렇게 하면 실용적인 시간으로 관련된 데이터로 됩니다.

 

df.index = pd.to_datetime(df['date'])
df = df.drop('date', axis=1)
df

이렇게 date를 index로 해준 다음 drop해줍니다.

 

 

# figure 생성 시 width와 height를 사용
p = figure(width=700, height=300, x_axis_type='datetime')

# 라인 플롯 생성
p.line(df.index, df['close'], color='navy', alpha=0.5)

# 플롯 표시
show(p)

script, div = components(p)
script

 

d

이렇게 script로 나오게 됩니다.

import jinja2
from bokeh.embed import components
template = jinja2.Template('''\
<html>
<link href='http://cdn.pydata.org/bokeh/release/bokeh-1.0.2.min.css' rel='stylesheet' type='text/css'>
<script src='http://cdn.pydata.org/bokeh/release/bokeh-1.0.2.min.js'></script>
<head><title>bokeh test</title>
<head>
<body>
<h1>This site for Bokeh Test</h1>

This site is the place for test.
{{script}}
{{div}}}

</body>
</html>
'''
)
from IPython.display import HTML
HTML(template.render(script=script, div=div))

with open('a.html', 'w') as f:
  f.write(template.render(script=script, div=div))

  import webbrowser

  webbrowser.open('a.html')

이렇게 웹에 표시할 수 있는 방법이 있습니다.