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

Tạo Scatter plot màu sắc có tooltip hover với Bokeh


Bokeh: package Python trực quan hóa, mã nguồn mở, render HTML/JS → dashboard web.

Tương thích NumPy, Pandas. Bokeh tạo biểu đồ tương tác (interactive) khác với Matplotlib/Seaborn (static). Nhúng vào Flask/Django/Jupyter.

Dependencies: NumPy, Pillow, Jinja2, Packaging, PyYAML, Six, Tornado, python-dateutil.

Cài đặt: pip3 install bokeh | conda install bokeh

Ví dụ

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

N = 5000
x = np.random.random(size=N) * 125
y = np.random.random(size=N) * 125
radii = np.random.random(size=N) * 1.35

colors = [
    "#%02x%02x%02x" % (int(r), int(g), 150)
    for r, g in zip(40+2*x, 30+2*y)
]

TOOLS = "hover,crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select"

p = figure(tools=TOOLS)
p.scatter(x, y, radius=radii, fill_color=colors, fill_alpha=0.6, line_color=None)

output_file("colorscatter.html", title="Color scatter plot")
show(p)

Đầu ra

Tạo Scatter plot màu sắc có tooltip hover với Bokeh

Giải thích

  • Import NumPy, Bokeh.
  • Sinh dữ liệu ngẫu nhiên 5000 điểm (x, y, radius).
  • Tạo màu RGB động dựa trên tọa độ.
  • Định nghĩa TOOLS bao gồm hover, zoom, select...
  • scatter() vẽ điểm với radius, color, alpha tùy biến.
  • output_file() + show() xuất HTML tương tác.