Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo biểu đồ lưới (grid plot) với thư viện Bokeh trong Python

Bokeh là thư viện trực quan hóa dữ liệu Python mã nguồn mở, hiển thị biểu đồ bằng HTML/JavaScript, phù hợp cho dashboard web.

Bokeh chuyển dữ liệu thành JSON, đưa vào BokehJS (viết bằng TypeScript) để render trên trình duyệt hiện đại.

Phụ thuộc & Cài đặt

# Phụ thuộc: NumPy, Pillow, Jinja2, Packaging, PyYAML, Six, Tornado, python-dateutil
pip3 install bokeh          # Windows
conda install bokeh         # Anaconda

Ví dụ: Grid plot (heatmap) với NumPy

import numpy as np
from bokeh.plotting import figure, output_file, show

N = 420
x = np.linspace(0, 14, N)
y = np.linspace(0, 14, N)
x1, y1 = np.meshgrid(x, y)
d = np.sin(x1) * np.cos(y1)

p = figure(tooltips=[("x", "$x"), ("y", "$y"), ("value", "@image")])
p.x_range.range_padding = p.y_range.range_padding = 0
p.image(image=[d], x=0, y=0, dw=11, dh=11, palette="Spectral11", level="image")
p.grid.grid_line_width = 0.6

output_file("gridplot.html", title="Ví dụ grid plot")
show(p)

Kết quả

Tạo biểu đồ lưới (grid plot) với thư viện Bokeh trong Python

Giải thích

  • Tạo dữ liệu 2D bằng np.meshgrid và hàm sin/cos.
  • Dùng figure() với tooltip hiển thị tọa độ và giá trị.
  • p.image() vẽ heatmap từ mảng 2D, áp dụng palette màu Spectral11.
  • output_file() lưu ra file HTML, show() mở trình duyệt.

Mẹo: Để tương tác tốt hơn, thêm công cụ HoverTool, PanTool, WheelZoomTool vào figure(tools=...).