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

วิธีเปลี่ยนสีเส้นตามดัชนีข้อมูลใน line graph matplotlib

ในการทำให้สีเส้นเปลี่ยนตามดัชนีข้อมูลสำหรับ line graph ใน matplotlib สามารถทำตามขั้นตอนดังนี้:

ขั้นตอน

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots

  • สร้างข้อมูล x และ y ด้วย numpy

  • ได้ขีดจำกัดเล็ก dydx

  • ได้ข้อมูล points และ segments ด้วย numpy

  • สร้าง figure และชุด subplots

  • สร้าง class ที่ normalize ข้อมูลเชิงเส้นเข้าในช่วง

  • ตั้งค่า image array จาก numpy array *A*

  • ตั้งค่า linewidth สำหรับ collection

  • ตั้งค่า colorbar สำหรับ axis 1

  • สร้าง Colormap object จากรายการสี r, g, b

  • ทำซ้ำขั้นตอน 6, 7, 8, 9, 10

  • ตั้งค่าขีดจำกัดแกน X และ Y

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

ตัวอย่าง

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(0, 3 * np.pi, 500)
y = np.sin(x)
dydx = np.cos(0.5 * (x[:-1] + x[1:]))
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
fig, axs = plt.subplots(2, 1, sharex=True, sharey=True)
norm = plt.Normalize(dydx.min(), dydx.max())
lc = LineCollection(segments, cmap='viridis', norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs[0].add_collection(lc)
fig.colorbar(line, ax=axs[0])
cmap = ListedColormap(['r', 'g', 'b'])
norm = BoundaryNorm([-1, -0.5, 0.5, 1], cmap.N)
lc = LineCollection(segments, cmap=cmap, norm=norm)
lc.set_array(dydx)
lc.set_linewidth(2)
line = axs[1].add_collection(lc)
fig.colorbar(line, ax=axs[1])
axs[0].set_xlim(x.min(), x.max())
axs[0].set_ylim(-1.1, 1.1)
plt.show()

ผลลัพธ์

จะแสดงสอง subplots: บน viridis colormap ตาม derivative ล่าง discrete colormap r/g/b ตามช่วง derivative

วิธีเปลี่ยนสีเส้นตามดัชนีข้อมูลใน line graph matplotlib