วิธีจัดเรียงแท่งใหม่ในแผนภูมิแท่งแบบเรียงซ้อนใน ggplot2
คุณสามารถใช้ไวยากรณ์พื้นฐานต่อไปนี้เพื่อจัดเรียงตำแหน่งของแท่งใหม่ในแผนภูมิแท่งแบบเรียงซ้อนใน ggplot2:
#specify order of bars (from top to bottom) df$fill_var <- factor(df$fill_var, levels=c(' value1 ', ' value2 ', ' value3 ', ...)) #create stacked bar chart ggplot(df, aes(x=x_var, y=y_var, fill=fill_var)) + geom_bar(position=' stack ', stat=' identity ')
ตัวอย่างต่อไปนี้แสดงวิธีใช้ไวยากรณ์นี้ในทางปฏิบัติ
ตัวอย่าง: จัดเรียงแท่งใหม่ในแผนภูมิแท่งแบบเรียงซ้อนใน ggplot2
สมมติว่าเรามีกรอบข้อมูลต่อไปนี้ใน R ที่แสดงคะแนนที่ทำโดยผู้เล่นบาสเกตบอลที่แตกต่างกัน:
#create data frame
df <- data. frame (team=c('A', 'A', 'A', 'B', 'B', 'B', 'C', 'C', 'C'),
position=c('G', 'F', 'C', 'G', 'F', 'C', 'G', 'F', 'C'),
points=c(22, 12, 10, 30, 12, 17, 28, 23, 20))
#view data frame
df
team position points
1 AG 22
2 AF12
3 AC 10
4 BG 30
5 BF 12
6 BC 17
7 GC 28
8 CF 23
9 CC 20
หากเราสร้างแผนภูมิแท่งแบบเรียงซ้อนเพื่อให้เห็นภาพคะแนนที่ผู้เล่นในแต่ละทีมทำได้ ggplot2 จะเรียงแท่งตามลำดับตัวอักษรโดยอัตโนมัติ:
library (ggplot2) #create stacked bar chart ggplot(df, aes(x=team, y=points, fill=position)) + geom_bar(position=' stack ', stat=' identity ')

โปรดทราบว่าแต่ละแท่งแบบเรียงซ้อนจะแสดงตำแหน่ง (บนลงล่าง) ตามลำดับตัวอักษร
ในการจัดเรียงแท่งใหม่ในลักษณะเฉพาะ เราสามารถแปลงตัวแปรตำแหน่งเป็นปัจจัย และใช้อาร์กิวเมนต์ ระดับ เพื่อระบุลำดับที่แท่งควรอยู่ (บนลงล่าง) ในแผนภูมิแท่งแบบเรียงซ้อน:
library (ggplot2) #convert 'position' to factor and specify level order df$position <- factor(df$position, levels=c(' F ', ' G ', ' C ')) #create stacked bar chart ggplot(df, aes(x=team, y=points, fill=position)) + geom_bar(position=' stack ', stat=' identity ')

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