Bokeh는 웹 친화적인 인터랙티브 데이터 시각화를 구축하기 위한 Python 라이브러리입니다. 순수 Python 코드로 풍부한 그래픽을 생성하고 BokehJS 런타임 엔진을 통해 웹 브라우저에서 직접 렌더링합니다.
The core Bokeh construction equation:
$$\text{Figure (캔버스)} + \text{ColumnDataSource (데이터)} + \text{Glyphs (시각적 마커)} = \text{대화형 시각화}$$
🔗 관련 치트 시트: Pandas 치트 시트 · NumPy 치트 시트 · Scikit-Learn 치트 시트 · 데이터 분석 방법 · Python 치트 시트
1. 실무 앤드투앤드 빠른 시작 예제
다음 스크립트는 데이터를 생성하고 캔버스를 초기화하며, 선과 원 글리프를 렌더링하고, 대화형 호버 도구 설명을 설정하여 독립 실행형 HTML 파일로 출력합니다:
from bokeh.plotting import figure, show
from bokeh.io import output_file
from bokeh.models import ColumnDataSource, HoverTool
# 1. 데이터 소스 준비
data = {
'x': [1, 2, 3, 4, 5],
'y': [6, 7, 2, 4, 8],
'label': ['A', 'B', 'C', 'D', 'E']
}
source = ColumnDataSource(data=data)
# 2. Figure 캔버스 초기화 (Bokeh 3.x에서는 width/height 사용)
p = figure(
title="Daily Temperature Trend",
x_axis_label="Day",
y_axis_label="Temperature (°C)",
width=700,
height=400,
tools="pan,wheel_zoom,box_zoom,reset,save"
)
# 3. 글리프 추가 (선 및 원형 마커)
p.line(x='x', y='y', source=source, line_width=2, color="#1f77b4", legend_label="Observed")
circles = p.circle(x='x', y='y', source=source, size=10, fill_color="white", line_color="#1f77b4", line_width=2)
# 4. HoverTool 연결
hover = HoverTool(
renderers=[circles],
tooltips=[("Sample", "@label"), ("Day", "$x{0}"), ("Temp", "$y{0.0} °C")]
)
p.add_tools(hover)
# 5. 파일 출력 및 브라우저 표시
output_file("trend.html", title="Bokeh Trend Visualization")
show(p)
2. 핵심 데이터 컨테이너: ColumnDataSource
ColumnDataSource (CDS)는 Bokeh의 핵심 데이터 래퍼입니다. 데이터를 CDS로 감싸면 다중 플롯 간 연동, 스트리밍 실시간 업데이트 및 클라이언트 측 브러싱이 가능해집니다:
import pandas as pd
from bokeh.models import ColumnDataSource
# 1. Pandas DataFrame 또는 딕셔너리로 생성
df = pd.DataFrame({
'mpg': [18.0, 15.0, 18.0, 16.0],
'hp': [130, 165, 150, 150],
'origin': ['USA', 'USA', 'USA', 'Europe']
})
source = ColumnDataSource(df)
# 2. 내부 열 배열 접근
mpg_values = source.data['mpg']
# 3. 새로운 데이터 스트리밍 (실시간 대시보드 / 텔레메트리)
new_data = {'mpg': [20.0], 'hp': [140], 'origin': ['Japan']}
source.stream(new_data, rollover=1000) # rollover: 1000개를 초과하는 가장 오래된 데이터 자동 삭제
# 4. 부분 인플레이스 업데이트 (전체 재렌더링 방지)
source.patch({
'hp': [(0, 135)] # 인덱스 0의 hp 값을 135로 교체
})
3. 캔버스 구성 (figure())
⚠️ 주의: Bokeh 3.0+에서는
plot_width와plot_height가 완전히 제거되었습니다. 반드시width와height를 사용하세요.
from bokeh.plotting import figure
p = figure(
title="Main Chart",
width=800, # 너비 (픽셀)
height=500, # 높이 (픽셀)
x_range=(0, 100), # 축 범위 제한 (또는 범주형 리스트 ['A', 'B'])
y_range=(0, 50),
x_axis_type="datetime", # 축 타입: 'linear', 'log', 'datetime', 'mercator'
tools="pan,box_zoom,wheel_zoom,reset,save",
toolbar_location="right", # 도구 모음 위치: 'above', 'below', 'left', 'right', None
background_fill_color="#fafafa"
)
# 축 스타일 설정
p.xaxis.axis_label = "Timeline"
p.xaxis.axis_label_text_font_size = "12pt"
p.grid.grid_line_dashed = [4, 4]
4. 시각적 글리프 마스터 인덱스
| 글리프 범주 | 메서드 구문 | 주요 매개변수 및 설명 |
|---|---|---|
| 원 / 포인트 | p.circle(x, y, ...) |
size=10, fill_color, line_color, fill_alpha |
| 정사각형 | p.square(x, y, ...) |
size, fill_color |
| 범용 산점도 | p.scatter(x, y, marker="hex", ...) |
통합 산점도: marker는 'circle', 'triangle', 'cross', 'star' 등 가능 |
| 연속 직선 | p.line(x, y, ...) |
line_width=2, line_color, line_dash='dashed' |
| 계단식 선 | p.step(x, y, mode="after", ...) |
계단식 곡선: mode는 'before', 'after', 'center' |
| 다중 선 | p.multi_line(xs, ys, ...) |
xs=[[x1, x2], [x3, x4]], ys=[[y1, y2], [y3, y4]] |
| 수직 막대 | p.vbar(x, width, top, bottom=0) |
막대형 차트: x는 중심 좌표, top은 막대 높이 |
| 수평 막대 | p.hbar(y, height, right, left=0) |
수평 막대 차트: y는 중심 좌표, right는 막대 길이 |
| 영역 채우기 | p.varea(x, y1, y2, ...) |
두 곡선 사이 채워진 영역 (오차 범위, 신뢰 구간) |
| 닫힌 다각형 | p.patch(x, y, ...) |
닫힌 2D 다각형 영역 채우기 |
5. 색상 매핑 및 팔레트 (bokeh.transform)
5.1 범주형 색상 매핑 (factor_cmap)
from bokeh.transform import factor_cmap
from bokeh.palettes import Category10
factors = ['USA', 'Asia', 'Europe']
palette = Category10[3] # 3색 팔레트
color_mapping = factor_cmap(
field_name='origin',
palette=palette,
factors=factors
)
p.circle(
x='mpg', y='hp', source=source,
color=color_mapping,
legend_field='origin', # origin 값에 따라 범례 항목을 자동으로 분할
size=9
)
5.2 연속형 선형 색상 매핑 (linear_cmap 및 ColorBar)
from bokeh.transform import linear_cmap
from bokeh.palettes import Viridis256
from bokeh.models import ColorBar
mapper = linear_cmap(
field_name='hp',
palette=Viridis256,
low=min(df['hp']),
high=max(df['hp'])
)
p.circle(x='mpg', y='hp', source=source, color=mapper, size=8)
# 측면에 컬러바 눈금 추가
color_bar = ColorBar(color_mapper=mapper['transform'], width=12, location=(0, 0))
p.add_layout(color_bar, 'right')
6. 대화형 인터랙션 및 선택 스타일
6.1 맞춤형 마우스 호버 툴팁 (HoverTool)
from bokeh.models import HoverTool
hover = HoverTool(
tooltips=[
("Origin", "@origin"),
("MPG", "@mpg{0.0}"),
("Horsepower", "@hp hp"),
("Pixel Coordinate", "($sx, $sy)")
],
formatters={
'@timestamp': 'datetime'
},
mode='mouse' # 'mouse'는 개별 포인트 호버; 'vline'은 수직선 기준 탐색
)
p.add_tools(hover)
6.2 선택 및 비선택 상태 스타일링
p.circle(
x='mpg', y='hp', source=source,
size=10,
color="blue",
selection_color="red", # 선택된 포인트는 빨간색으로 표시
nonselection_alpha=0.1 # 선택되지 않은 포인트는 10% 투명도로 흐려짐
)
7. 범례 및 클릭 정책
⚠️ 주의: Bokeh 2.0+ 및 3.x+에서는
legend='xxx'가 지원 중단되었습니다. 고정 레이블에는legend_label='이름', 열 기준 그룹화에는legend_field='열'을 사용하세요.
# 1. 범례 위치 및 레이아웃 설정
p.legend.location = "top_right" # 'top_left', 'bottom_right', 'center' 등
p.legend.orientation = "horizontal" # 'vertical' 또는 'horizontal'
p.legend.background_fill_alpha = 0.8
p.legend.border_line_color = "#e0e0e0"
# 2. 인터랙티브 토글 (범례 클릭 시 해당 레이어 숨김/표시)
p.legend.click_policy = "hide" # 옵션: 'hide' 또는 'mute'
8. 다중 플롯 레이아웃 및 연동 동기화
8.1 그리드 레이아웃 (row, column, gridplot)
from bokeh.layouts import row, column, gridplot
# 수평 행 배치
layout_row = row(p1, p2, p3)
# 수직 열 배치
layout_col = column(p1, p2)
# 중첩 그리드 배치
grid = gridplot([[p1, p2], [p3, p4]], width=350, height=300)
8.2 탭 레이아웃 (TabPanel 및 Tabs)
⚠️ 주의: Bokeh 3.0+에서는
Panel이 제거되고bokeh.models의TabPanel로 완전히 대체되었습니다.
from bokeh.models import TabPanel, Tabs
tab1 = TabPanel(child=p1, title="Revenue")
tab2 = TabPanel(child=p2, title="User Growth")
tabs_layout = Tabs(tabs=[tab1, tab2])
show(tabs_layout)
8.3 플롯 간 상호 작용 연동
팬 및 줌 연동
한 플롯의 축 범위를 다른 플롯에 할당합니다:
p2.x_range = p1.x_range
p3.x_range = p1.x_range
연동 브러싱 (Linked Brushing)
여러 Figure에서 동일한 ColumnDataSource 인스턴스를 공유합니다:
# p1과 p2가 동일한 `source`를 공유
p1 = figure(width=350, height=300, tools="box_select,lasso_select,reset")
p1.circle('mpg', 'hp', source=source)
p2 = figure(width=350, height=300, tools="box_select,lasso_select,reset")
p2.circle('mpg', 'weight', source=source)
# p1에서 데이터 포인트를 선택하면 p2의 대응 데이터도 함께 강조됨
show(row(p1, p2))
9. 출력, 웹 임베딩 및 정적 내보내기
| 출력 대상 | 실행 환경 / 프레임워크 | 코드 스니펫 |
|---|---|---|
| Jupyter Notebook | 노트북 환경 내 인터랙티브 개발 | from bokeh.io import output_notebook, showoutput_notebook()show(p) |
| 독립 실행형 HTML | CDN 자바스크립트를 활용한 오프라인 배포 | from bokeh.io import output_file, saveoutput_file("chart.html", mode='cdn')save(p) |
| 웹 애플리케이션 (FastAPI/Flask/Django) | components 함수로 HTML 템플릿에 직접 임베딩 | from bokeh.embed import componentsscript, div = components(p) |
| 정적 PNG 이미지 | 보고서 및 정적 문서화 | from bokeh.io import export_pngexport_png(p, filename="plot.png") |
| 벡터 SVG 이미지 | 고해상도 인쇄 및 학술 논문 게재 | from bokeh.io import export_svgp.output_backend = "svg"export_svg(p, filename="plot.svg") |