Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีแสดงกราฟ Twin Axes (สองแกน Y) ด้วย Bokeh ใน Python

บทนำ

Bokeh สร้างกราฟแบบโต้ตอบ (interactive) ต่างจาก Matplotlib/Seaborn ที่เป็น static plots สามารถฝังใน Flask, Django, Jupyter Notebook ได้

การติดตั้ง

pip3 install bokeh
conda install bokeh

ตัวอย่างโค้ด

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='Twin Axis plot', plot_width=300, plot_height=300, y_range=(-0.7, 0.7))
my_fig.line(x, y, color="blue")

# เพิ่มแกน Y ด้านขวา
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)

คำอธิบาย

  • สร้างข้อมูล sine wave และ linear space

  • สร้าง figure หลักพร้อมแกน Y ซ้าย

  • เพิ่ม extra_y_ranges สำหรับแกน Y ขวา

  • ใช้ add_layout วาง LinearAxis ด้านขวา

  • พลอตเส้นที่สองระบุ y_range_name="y2"