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

Bar Chart ด้วย Vertical Labels ใน Python/Matplotlib


ก่อนอื่น เราสามารถสร้าง Bars โดยใช้ plt.bar และใช้ xticks จากนั้นเราสามารถจัดตำแหน่ง Labels โดยตั้งค่า Attribute "vertical" หรือ "horizontal" ใน Key "rotation"

ขั้นตอน

  • สร้าง Lists bars_heights และ bars_label ด้วยตัวเลข
  • สร้าง Bar Plot โดยใช้เมธอด bar() ด้วย bars_heights และความยาวของ bars_label
  • ดึงหรือตั้งค่า Current Tick Locations และ Labels ของ X-axis โดยใช้ xticks() ด้วย rotation='vertical' และ bars_label
  • เพื่อแสดง Plot ใช้เมธอด plt.show()

ตัวอย่าง

from matplotlib import pyplot as plt

bars_heights = [14, 8, 10]
bars_label = ["A label", "B label", "C label"]
plt.bar(range(len(bars_label)), bars_heights)
plt.xticks(range(len(bars_label)), bars_label, rotation='vertical')
plt.show()

ผลลัพธ์

Bar Chart ด้วย Vertical Labels ใน Python/Matplotlib