我有这个数据框
library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
count = c(4,3,4,5))
dat %>% arrange(parent,-count )
parent group value count
1 F D(5) 4 5
2 F A(4) 3 4
3 J A(4) 1 4
4 J C(3) 2 3
您可以看到上面的数据按父级排序,然后以递减计数。我希望图表保持这种顺序,但是当我在“J”图表中绘制时,C(3)出现在A(4)之上并且应该受到尊重。怎么办?
ggplot(dat, aes(x = group, y= value))+
geom_bar(stat ="identity",position = "dodge")+
coord_flip()+
facet_wrap(~parent, scale = "free_y")
答案 0 :(得分:1)
您可以使用当前排序的值作为级别在组列上设置因子(反转以获得所需的顺序)。这将锁定订单。
library(dplyr)
dat =data.frame(parent = c("J","J","F","F"),group= c("A(4)","C(3)","A(4)","D(5)"),value=c(1,2,3,4),
count = c(4,3,4,5))
dat <- dat %>% arrange(parent,-count )
dat$group <- factor(dat$group, levels = rev(unique(dat$group)))
ggplot(dat, aes(x = group, y= value))+
geom_bar(stat ="identity",position = "dodge")+
coord_flip()+
facet_wrap(~parent, scale = "free_y")
答案 1 :(得分:0)
您可以尝试:
dat %>% arrange(parent,-count ) %>%
mutate(group2=factor(c(2,1,4,3))) %>%
ggplot(aes(x = group2, y= value))+
geom_bar(stat ="identity",position = "dodge")+
coord_flip()+
facet_wrap(~parent, scale = "free_y")+
scale_x_discrete(breaks=1:4,labels = c("A(4)","D(5)","C(3)","A(4)"))