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

การกำหนดขนาดกริดบนกราฟใน Matplotlib


ตั้งค่าตำแหน่ง grid lines เอง

ใช้ set_ticks กำหนดตำแหน่ง grid แล้วเปิด grid(True)

ขั้นตอน

  1. สร้าง figure ด้วย figure()
  2. เพิ่ม axes ด้วย add_subplot()
  3. วาดกราฟด้วย list ข้อมูล
  4. ตั้งค่า margins x, y เป็น 0
  5. กำหนดตำแหน่ง X-grid ด้วย set_ticks()
  6. เปิด grid lines ด้วย grid(True)
  7. แสดงด้วย show()

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

from matplotlib import pyplot as plt

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

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0, 2, 5, 8, 10, 1, 3, 14], 'ro-')
ax.margins(x=0, y=0)

grid_points = [1., 2., 3., 10.]
ax.xaxis.set_ticks(grid_points)
ax.grid(True)
plt.show()

ผลลัพธ์

การกำหนดขนาดกริดบนกราฟใน Matplotlib