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

Trực quan hóa trục đôi (twin axes) với Bokeh trong Python

Bokeh tạo biểu đồ tương tác (interactive) thay vì tĩnh như Matplotlib/Seaborn. Có thể nhúng vào Flask, Django, Jupyter Notebook.

Cài đặt

pip3 install bokeh
conda install bokeh

Ví dụ: Biểu đồ hai trục Y


from numpy import pi, arange, sin, linspace
from bokeh.plotting import output_file, figure, show
from bokeh.models import LinearAxis, Range1d

x = arange(-2.5*pi, 2.5*pi, 0.15)
y = sin(x)
y2 = linspace(0, 176, len(y))

my_fig = figure(title='Biểu đồ trục đôi', plot_width=300, plot_height=300, y_range=(-0.7, 0.7))
my_fig.line(x, y, color="blue")

# Thêm trục Y thứ 2 bên phải
my_fig.extra_y_ranges = {"y2": Range1d(start=0, end=100)}
my_fig.add_layout(LinearAxis(y_range_name="y2"), 'right')
my_fig.line(x, y2, color="cyan", y_range_name="y2")

show(my_fig)

Kết quả

Trực quan hóa trục đôi (twin axes) với Bokeh trong Python

Giải thích

  • Tạo dữ liệu: sin(x) và dãy tuyến tính y2.
  • Tạo figure với trục Y chính (y_range).
  • Vẽ đường thứ nhất (màu xanh).
  • Định nghĩa extra_y_ranges cho trục thứ 2, thêm LinearAxis bên phải.
  • Vẽ đường thứ hai gán y_range_name="y2".

Ứng dụng: So sánh hai chuỗi thời gian có thang đo khác nhau (ví dụ: nhiệt độ và độ ẩm).