[英]R: reorder geom_bar(stat = “identity”, position=position_dodge()) by value of one of two factors
我有一個玩具數據表
library(data.table)
library(ggplot2)
set.seed(45L)
DT <- data.table(V1=c(1L,2L),
V2=LETTERS[1:3],
Value=c(1,3,5,3,2,4,6,7,7,5,4,2),
V4=c(1,1,2,2,3,3,4,4,5,5,6,6))
和ggplot代碼
ggplot(DT, aes(x=factor(V4), y=V3, fill= factor(V1)))+
geom_bar(stat = "identity", position=position_dodge())+
theme(axis.text.x = element_text(angle = 45, hjust = 1),
axis.line.x = element_line(),
axis.line.y = element_line(),
panel.background = element_blank())
結果如下圖
我想通過V1因子1的值對x軸重新排序。因此,結果順序將為5,4,2,6,3,1。
任何幫助將不勝感激!
您的排序取決於其他兩個變量,因此可以使用forcats::fct_reorder2()
:
library(forcats)
ggplot(DT, aes(x=fct_reorder2(factor(V4), V1, Value, function(x, y) {sum(y[x == 1])}),
y=Value, fill= factor(V1)))+
geom_bar(stat = "identity", position=position_dodge())+
labs(x = "V4") +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
axis.line.x = element_line(),
axis.line.y = element_line(),
panel.background = element_blank())
我通常在調用ggplot之前在管道中進行這種數據准備。 所以:
DT[, .SD
][, V1Val := Value[V1 == 1], V4
][order(-V1Val, V4)
][, V4 := factor(V4, levels=unique(V4))
][, V1 := factor(V1)
][, ggplot(.SD, aes(x=V4, y=Value, fill=V1))
+ geom_bar(stat="identity", position=position_dodge())
+ theme(axis.text.x=element_text(angle=45, hjust=1),
axis.line.x=element_line(),
axis.line.y=element_line(),
panel.background=element_blank())
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.