Mô tả
Bokeh là thư viện visualization tương tác cho web. Xuất ra HTML/JS, hiển thị trên browser, hỗ trợ zoom, pan, hover, v.v.
Cài đặt
pip install bokeh
1. Vẽ đường (Line Plot)
from bokeh.io import show, output_file
from bokeh.plotting import figure
# output_file("line.html") # Lưu file HTML thay vì show browser
p = figure(plot_width=400, plot_height=300, title="Line Plot")
p.line([2, 1, 2, 4], [1, 3, 5, 4], line_width=2, color="blue", legend_label="Line")
p.legend.location = "top_left"
show(p)
2. Vẽ điểm tròn (Scatter/Circle)
from bokeh.io import show
from bokeh.plotting import figure
p = figure(plot_width=400, plot_height=300, title="Scatter Plot")
p.circle([2, 1.5, 2, 3, 2.4], [2, 3, 4, 4, 3],
size=10, color="red", alpha=0.8, legend_label="Points")
show(p)
3. Vẽ biểu đồ cột (Bar Chart)
from bokeh.io import show from bokeh.plotting import figure categories = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] values = [6, 3, 4, 2, 4] p = figure(x_range=categories, plot_height=250, title="Sales Figures") p.vbar(x=categories, top=values, width=0.4, color="navy", legend_label="Sales") # Tùy chỉnh giao diện p.xgrid.grid_line_color = None p.y_range.start = 0 p.legend.orientation = "horizontal" p.legend.location = "top_center" show(p)
4. Tương tác: Hover Tool
from bokeh.models import HoverTool, ColumnDataSource
source = ColumnDataSource(data=dict(
x=[1,2,3,4,5],
y=[2,5,8,2,7],
label=['A','B','C','D','E']
))
p = figure(plot_width=400, plot_height=300, tools="hover,pan,wheel_zoom,reset")
p.circle('x', 'y', size=10, source=source)
hover = p.select(HoverTool)
hover.tooltips = [
("Label", "@label"),
("X", "@x"),
("Y", "@y"),
]
show(p)
5. Lưu file HTML
from bokeh.io import output_file, save
from bokeh.plotting import figure
output_file("my_plot.html")
p = figure(...)
# ... vẽ ...
save(p) # Tạo file my_plot.html có thể mở trình duyệt
So sánh với Matplotlib/Seaborn
| Đặc điểm | Bokeh | Matplotlib |
|---|---|---|
| Output | HTML/JS (Interactive) | Static image (PNG, PDF) |
| Web embedding | Dễ dàng | Cần chuyển đổi |
| Large data | WebGL support | Chậm |
| Learning curve | Trung bình | Thấp |