问题描述
我希望我可以按降序对每个方面的值进行排序。
我使用了reorder (Agent,-value)
,但是它不起作用。
我的一部分数据:
Country Agent Period Level Location variable value
361 e L 2016_2017 1 d 11 8
362 e S 2016_2017 1 d 11 1
363 e C 2016_2017 1 d 11 12
364 e B 2016_2017 1 d 11 6
365 e A 2016_2017 1 d 11 5
366 e D 2016_2017 1 d 11 2
我的简化代码:
library(ggplot2)
# toy data
data = data.frame(Country = c("e","e","e"),Agent = c("L","S","C","B","A","D","L","D"),Period = c("2016_2017","2016_2017","2014_2015","2011_2012","2011_2012"),Level = c("1","1","1"),Location = c("d","d","d"),variable = c("11","11","21","21"),value = c(8,1,12,6,5,2,4,3))
# most importants parts of my plot,related to the question
ggplot(data,aes(x = reorder (Agent,-value),y = value)) +
geom_bar(position = "dodge",stat = 'identity') +
facet_grid(Period~variable,scales = "free",space="free")
解决方法
您可以尝试这种方法。 reorder_within()
包中的函数tidytext
允许在深层次上重新排序,就像在图的aes()
项中看到的那样。我重用了您发布的代码并包含了修改:
library(tidytext)
library(ggplot2)
#Plot
ggplot(subset(data,Country %in% c("e") & Level %in% c("1") & Location %in% c("d")),aes(x = reorder_within(Agent,-value,variable),y = value,colour = Agent)) +
geom_bar(position = "dodge",stat = 'identity')+
facet_grid(Period~variable,scales = "free",space="free") +
theme_bw() +
theme(plot.title = element_text(size = 14,face = "bold"),text = element_text(size = 12,family = ""),axis.title = element_text(face="bold"),axis.title.x = element_blank(),axis.title.y = element_blank(),axis.text.x = element_blank(),axis.ticks.x = element_blank(),strip.text.x = element_text(size = 10,colour = "Black",angle = 0),strip.text.y = element_text(size = 10,legend.position = "none")
输出: