วิธีเปลี่ยนลำดับของแท่งใน seaborn barplot


คุณสามารถใช้วิธีการต่อไปนี้เพื่อเปลี่ยนลำดับของแท่งในพล็อต ทางทะเล :

วิธีที่ 1: แถบจัดเรียงใน Barplot ที่สร้างจากข้อมูลดิบ

 sns. barplot (x=' xvar ', y=' yvar ', data=df, order=df. sort_values (' yvar '). xvar )

วิธีที่ 2: แถบจัดเรียงใน Barplot ที่สร้างจากข้อมูลที่รวบรวม

 sns. barplot (x=' xvar ', y=' yvar ', data=df, order=df_agg[' xvar ']

ตัวอย่างต่อไปนี้แสดงวิธีการใช้แต่ละวิธีในทางปฏิบัติ

ตัวอย่างที่ 1: แถบการจัดเรียงใน Barplot ที่สร้างจากข้อมูลดิบ

สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับยอดขายรวมของพนักงานหลายคนของบริษัท:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' employee ': ['Andy', 'Bert', 'Chad', 'Doug', 'Eric', 'Frank'],
                   ' sales ': [22, 14, 9, 7, 29, 20]})

#view DataFrame
print (df)

  employee sales
0 Andy 22
1 Bert 14
2 Chad 9
3 Doug 7
4 Eric 29
5 Frank 20

เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อสร้าง barplot ซึ่งแท่งจะถูกเรียงลำดับจากน้อยไปหามากตามมูลค่า การขาย :

 import seaborn as sns

#create barplot with bars sorted by sales values ascending
sns. barplot (x=' employee ', y=' sales ', data=df, order=df. sort_values (' sales '). employee )

หากต้องการจัดเรียงแท่งตามลำดับจากมากไปน้อย เพียงใช้ ascending=False ในฟังก์ชัน sort_values() :

 import seaborn as sns

#create barplot with bars sorted by sales values descending
sns. barplot (x=' employee ', y=' sales ', data=df,
            order=df. sort_values (' sales ', ascending= False ). employee ) 

ตัวอย่างที่ 2: แถบการเรียงลำดับใน Barplot ที่สร้างจากข้อมูลที่รวบรวม

สมมติว่าเรามี DataFrame แพนด้าต่อไปนี้ซึ่งมีข้อมูลเกี่ยวกับยอดขายรวมของพนักงานหลายคนของบริษัท:

 import pandas as pd

#createDataFrame
df = pd. DataFrame ({' employee ': ['A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'],
                   ' sales ': [24, 20, 25, 14, 19, 13, 30, 35, 28]})

#view DataFrame
print (df)

  employee sales
0 to 24
1 to 20
2 to 25
3 B 14
4 B 19
5 B 13
6 C 30
7 C 35
8 C 28

เราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อคำนวณมูลค่า การขาย เฉลี่ย โดยจัดกลุ่มตาม พนักงาน :

 #calculate mean sales by employee
df_agg = df. groupby ([' employee '])[' sales ']. mean (). reset_index (). sort_values (' sales ')

#view aggregated data
print (df_agg)

  employee sales
1 B 15.333333
0 to 23.000000
2 C 31.000000

จากนั้นเราสามารถใช้ไวยากรณ์ต่อไปนี้เพื่อสร้าง barplot ในทะเลที่แสดงยอดขายเฉลี่ยต่อพนักงานโดยแถบแสดงตามลำดับจากน้อยไปหามาก:

 import seaborn as sns

#create barplot with bars ordered in ascending order by mean sales
sns. barplot (x=' employee ', y=' sales ', data=df,
            order=df_agg[' employee '], errorbar=(' ci ', False )) 

แกน X จะแสดงชื่อของพนักงาน และแกน Y จะแสดงมูลค่าการขายเฉลี่ยของพนักงานแต่ละคน

แหล่งข้อมูลเพิ่มเติม

บทช่วยสอนต่อไปนี้จะอธิบายวิธีการทำหน้าที่ทั่วไปอื่นๆ ในทะเล:

วิธีแสดงค่าบน Seaborn Barplot
วิธีสร้าง barplot ที่จัดกลุ่มใน Seaborn
วิธีการตั้งค่าสีของแท่งใน barplot ของ Seaborn

เพิ่มความคิดเห็น

อีเมลของคุณจะไม่แสดงให้คนอื่นเห็น ช่องข้อมูลจำเป็นถูกทำเครื่องหมาย *