Pandas: วิธีสร้างแผนภูมิแท่งเพื่อแสดงภาพค่านิยม 10 อันดับแรก
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อสร้างแผนภูมิแท่งในรูปแบบแพนด้าที่รวมเฉพาะค่าที่พบบ่อยที่สุด 10 ค่าในคอลัมน์เฉพาะ:
import pandas as pd import matplotlib. pyplot as plt #find values with top 10 occurrences in 'my_column' top_10 = (df[' my_column ']. value_counts ()). iloc [:10] #create bar chart to visualize top 10 values top_10. plot (kind='bar')
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: สร้างแผนภูมิแท่งใน Pandas เพื่อให้เห็นภาพค่า 10 อันดับแรก
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับชื่อทีมและคะแนนที่ทำโดยผู้เล่นบาสเก็ตบอล 500 คน:
import pandas as pd import numpy as np from string import ascii_uppercase import random from random import choice #make this example reproducible random. seeds (1) n.p. random . seeds (1) #createDataFrame df = pd. DataFrame ({' team ': [choice(ascii_uppercase) for _ in range(500)], ' points ': np. random . uniform (0, 20, 500)}) #view first five rows of DataFrame print ( df.head ()) team points 0 E 8.340440 1 S 14.406490 2 Z 0.002287 3 Y 6.046651 4 C 2.935118
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อสร้างแผนภูมิแท่งที่แสดงค่าที่พบบ่อยที่สุด 10 ค่าในคอลัมน์ ทีม :
import matplotlib. pyplot as plt #find teams with top 10 occurrences top_10_teams = (df[' team ']. value_counts ()).[:10] #create bar chart of top 10 teams top_10_teams. plot (kind=' bar ')

กราฟแท่งประกอบด้วยชื่อของทีมที่เข้าบ่อยที่สุด 10 ทีม
แกน x จะแสดงชื่อทีมและแกน y จะแสดงความถี่
โปรดทราบว่าเรายังปรับแต่งโครงเรื่องเพื่อให้มีความสวยงามมากขึ้นได้:
import matplotlib. pyplot as plt #find teams with top 10 occurrences top_10_teams = (df[' team ']. value_counts ()).[:10] #create bar chart of top 10 teams top_10_teams. plot (kind=' bar ', edgecolor=' black ', rot=0) #add axis labels plt. xlabel (' Team ') plt. ylabel (' Frequency ')

โปรดทราบว่าอาร์กิวเมนต์ edgecolor เพิ่มเส้นขอบสีดำรอบๆ แต่ละแท่ง และอาร์กิวเมนต์ rot จะหมุนป้ายกำกับแกน x 90 องศาเพื่อให้อ่านง่ายขึ้น
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
Pandas: วิธีสร้างแผนภูมิแท่งแบบเรียงซ้อน
Pandas: วิธีใส่คำอธิบายประกอบแท่งในพล็อตแท่ง
Pandas: วิธีลงจุดหลายคอลัมน์บนแผนภูมิแท่ง