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

วิธาสร้าง Grid Plot ด้วยไลบรารี Bokeh ใน Python

บทนำ

Bokeh เป็นแพ็กเกจ Python สำหรับการแสดงภาพข้อมูล (Data Visualization) โครงการโอเพนซอร์ส ใช้ HTML และ JavaScript ในการเรนเดอร์.plot เหมาะสำหรับแดชบอร์ดบนเว็บ

Bokeh แปลงแหล่งข้อมูลเป็นไฟล์ JSON ซึ่งเป็นอินพุตของ BokehJS (ไลบรารี JavaScript เขียนด้วย TypeScript) เพื่อแสดงผลบนเบราว์เซอร์สมัยใหม่

การติดตั้ง

# Windows
pip3 install bokeh

# Anaconda
conda install bokeh

Dependencies

Numpy, Pillow, Jinja2, Packaging, Pyyaml, Six, Tornado, Python-dateutil

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

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="grid plot example")
show(p)

คำอธิบาย

  • นำเข้าแพ็กเกจ numpy และ bokeh

  • สร้างข้อมูล grid ด้วย np.meshgrid และคำนวณค่า sin*cos

  • สร้าง figure พร้อม tooltip

  • ใช้ p.image แสดงภาพ grid พร้อม palette สี

  • ตั้งค่า grid line width

  • บันทึกเป็นไฟล์ HTML และแสดงผล