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

วิธีทำ xticks ห่างกันเท่าๆ กันแม้ค่าจะไม่เท่ากัน (Matplotlib)


เพื่อทำ xticks ให้ห่างกันเท่าๆ กันแม้ค่าข้อมูลจะไม่เท่ากัน ใช้เมธอด set_ticks() และ set_ticklabels()

ขั้นตอน

  • ตั้งค่าขนาดรูปและ padding ระหว่าง subplots
  • สร้างข้อมูล x และ y ด้วย numpy
  • สร้าง figure และ subplots ด้วย subplots()
  • พลอต x และ y บนแกน 1
  • ตั้ง xticks ด้วย xaxis.set_ticks()
  • พลอต x และ y บนแกน 2
  • ตั้ง xticks และ ticklabels ด้วย xaxis.set_ticks() และ xaxis.set_ticklabels()
  • แสดงรูปด้วย show()

ตัวอย่าง

import numpy as np
from matplotlib import pyplot as plt

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

x = np.array([1, 1.5, 3, 5, 6])
y = np.power(2, x)

fig, (ax1, ax2) = plt.subplots(2, 1)
ax1.plot(x, y)
ax1.xaxis.set_ticks(x)
ax2.plot(x, y)
ax2.xaxis.set_ticks(range(len(x)))
ax2.xaxis.set_ticklabels(x)
plt.show()

ผลลัพธ์

วิธีทำ xticks ห่างกันเท่าๆ กันแม้ค่าจะไม่เท่ากัน (Matplotlib)