วิธีเปลี่ยนช่วงของแกน x ในฮิสโตแกรมของ pandas
คุณสามารถใช้อาร์กิวเมนต์ range เพื่อเปลี่ยนช่วงของแกน x ในฮิสโตแกรมแพนด้า:
plt. hist (df[' var1 '], range=[ 10 , 30 ])
ในตัวอย่างนี้ เราตั้งค่าแกน x ไว้ระหว่าง 10 ถึง 30
ตัวอย่างต่อไปนี้แสดงวิธีการใช้อาร์กิวเมนต์ range ในทางปฏิบัติ
ตัวอย่าง: การเปลี่ยนช่วงของแกน X ในฮิสโตแกรมของแพนด้า
สมมติว่าเรามี DataFrame แพนด้าดังต่อไปนี้:
import pandas as pd import numpy as np #make this example reproducible n.p. random . seeds (1) #createDataFrame df = pd. DataFrame ({' team ': np.repeat ([' A ',' B ',' C '], 100 ), ' points ': np. random . normal (loc= 20 , scale= 2 , size= 300 )}) #view head of DataFrame print ( df.head ()) team points 0 A 23.248691 1 A 18.776487 2 A 18.943656 3 A 17.854063 4 A 21.730815
หากเราสร้างฮิสโตแกรมสำหรับตัวแปร จุด แพนด้าจะเลือกช่วงแกน x โดยอัตโนมัติตามค่าต่ำสุดและสูงสุดของตัวแปร จุด :
import matplotlib.pyplot as plt #create histogram for variable points plt. hist (df[' points '], edgecolor=' black ')

แกน x ไปจาก 14 ถึง 25
เราสามารถใช้ฟังก์ชัน อธิบาย() เพื่อแสดงค่าต่ำสุดและสูงสุดของตัวแปร จุด :
#summarize distribution of points variable
df[' points ']. describe ()
count 300.000000
mean 20.148800
std 1.890841
min 14.413830
25% 18.818254
50% 20.176352
75% 21.372843
max 25.056651
Name: points, dtype: float64
เราจะเห็นว่าค่าต่ำสุดคือ 14.41 และค่าสูงสุดคือ 25.06 ซึ่งอธิบายได้ว่าเหตุใดแกน x ในแผนภูมิจึงอยู่ในช่วงตั้งแต่ 14 ถึง 25
อย่างไรก็ตาม เราสามารถใช้อาร์กิวเมนต์ range เพื่อบังคับให้แกน x ไปจาก 10 ถึง 30:
import matplotlib.pyplot as plt #create histogram for points variable with custom x-axis range plt. hist (df[' points '], edgecolor=' black ', range=[ 10 , 30 ])

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