Pandas: สร้างฮิสโตแกรมสำหรับแต่ละคอลัมน์ใน dataframe
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อสร้างฮิสโตแกรมสำหรับแต่ละคอลัมน์ของ DataFrame ของแพนด้า:
import pandas as pd import matplotlib. pyplot as plt #define number of subplots fig, axis = plt. subplots (1, 3) #create histogram for each column in DataFrame df. hist (ax=axis)
ตัวอย่างนี้ใช้ฟังก์ชัน subplots() เพื่อระบุว่ามี 3 คอลัมน์ใน DataFrame จากนั้นสร้างฮิสโตแกรมสำหรับแต่ละคอลัมน์
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: สร้างฮิสโตแกรมสำหรับแต่ละคอลัมน์ในฮิสโตแกรมของ Pandas
สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีสามคอลัมน์:
import pandas as pd import numpy as np #make this example reproducible n.p. random . seeds (1) #createDataFrame df = pd. DataFrame ({' points ': np. random . normal (loc=20, scale=2, size=300), ' assists ': np. random . normal (loc=14, scale=3, size=300), ' rebounds ': np. random . normal (loc=12, scale=1, size=300)}) #view head of DataFrame print ( df.head ()) points assists rebounds 0 23.248691 20.197350 10.927036 1 18.776487 9.586529 12.495159 2 18.943656 11.509484 11.047938 3 17.854063 11.358267 11.481854 4 21.730815 13.162707 10.538596
เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อสร้างฮิสโตแกรมสำหรับแต่ละคอลัมน์จากสามคอลัมน์ของ DataFrame:
import matplotlib. pyplot as plt
#define format for subplots (1 row and 3 columns)
fig, axis = plt. subplots (1, 3)
#create histogram for each column in DataFrame
df. hist (ax=axis)

ผลลัพธ์ที่ได้คือตารางที่มีหนึ่งแถวและสามคอลัมน์ที่แสดงฮิสโตแกรมสำหรับแต่ละคอลัมน์ของ DataFrame
หากคุณต้องการ คุณสามารถใช้อาร์กิวเมนต์ figsize เพื่อเปลี่ยนขนาดของฮิสโตแกรมตลอดจนอาร์กิวเมนต์ สีขอบ และ ตาราง เพื่อปรับปรุงลักษณะที่ปรากฏของฮิสโตแกรม:
import matplotlib. pyplot as plt
#define format for subplots
fig, axis = plt. subplots (1, 3, figsize=(8,3))
#create histogram for each column in DataFrame
df. hist (ax=axis, edgecolor=' black ', grid= False )

อย่าลังเลที่จะเล่นกับอาร์กิวเมนต์ของฟังก์ชัน subplots() เพื่อกำหนดรูปแบบและขนาดที่แน่นอนของฮิสโตแกรม
แหล่งข้อมูลเพิ่มเติม
บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำงานทั่วไปอื่นๆ ในแพนด้า:
วิธีเปลี่ยนจำนวนถังขยะที่ใช้ในฮิสโตแกรมของ Pandas
วิธีเปลี่ยนช่วงของแกน X ในฮิสโตแกรมของ Pandas
วิธีการพล็อตฮิสโตแกรมตามกลุ่มใน Pandas