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

การเพิ่มคุณภาพ Colormap และ Linewidth ใน Streamplot ของ Matplotlib

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots

  • สร้าง Figure และชุด Subplots

  • สร้างข้อมูล x และ y แล้วใช้ np.meshgrid() สร้างเมทริกซ์พิกัด

  • คำนวณ X และ Y จากข้อมูล x, y

  • สร้าง streamplot พร้อมเพิ่ม linewidth (ตัวอย่างใช้ 5) และ cmap

  • สร้าง Colorbar จาก ScalarMappable instance ของ stream.lines

  • แสดงรูปภาพด้วยเมธอด show()

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

import numpy as np
from matplotlib import pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

fig, ax = plt.subplots()
x, y = np.meshgrid(np.linspace(-5, 5, 20), np.linspace(-5, 5, 20))
X = y
Y = 3 * x - 4 * y

stream = ax.streamplot(x, y, X, Y,
    density=1, linewidth=5, cmap='plasma', color=Y)
fig.colorbar(stream.lines, ax=ax)
plt.show()

ผลลัพธ์

Streamplot ที่มีเส้นสายพาน (streamlines) หนาขึ้น (linewidth=5) ใช้ Colormap 'plasma' ตามค่า Y พร้อม Colorbar แสดงสเกลสี

เคล็ดลับ: การเพิ่ม linewidth ทำให้เห็นทิศทางสายพานชัดเจนขึ้น การใช้ color=Y ทำให้สีเปลี่ยนตามค่า Y แทนที่จะเป็นคงที่