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

วิธีหมุน Tick Labels ใน Subplot ด้วย Matplotlib


ภาพรวม

ใช้ set_xticklabels() และ set_yticklabels() พร้อมพารามิเตอร์ rotation เพื่อหมุนป้ายกำกับแกน

ขั้นตอน

  1. สร้างข้อมูล Tick positions
  2. สร้าง Subplot และตั้งค่า Ticks
  3. ตั้งค่า Tick Labels พร้อม rotation=45
  4. ปรับ Padding ระหว่าง Ticks และ Labels ด้วย tick_params(pad=15)
  5. ตั้งค่าทิศทาง Ticks ให้ชี้เข้าไปในกราฟ direction='in'

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

import matplotlib.pyplot as plt

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

x = [1, 2, 3, 4]
ax1 = plt.subplot()
ax1.set_xticks(x)
ax1.set_yticks(x)
ax1.set_xticklabels(["one", "two", "three", "four"], rotation=45)
ax1.set_yticklabels(["one", "two", "three", "four"], rotation=45)
ax1.tick_params(axis="both", direction="in", pad=15)
plt.show()

ผลลัพธ์

Tick Labels บนแกน X และ Y หมุน 45 องศา มีระยะห่างจากแกน 15 พิกเซล Ticks ชี้เข้าไปในกราฟ

พารามิเตอร์ tick_params ที่มีประโยชน์

  • axis='x'|'y'|'both'
  • which='major'|'minor'|'both'
  • direction='in'|'out'|'inout'
  • length, width, color, labelsize