无法在ggplot2 facet_grid(.~other_than_x_or_y)中重新排序标签

时间:2015-04-13 04:06:27

标签: r ggplot2 facet

我想重新排序这样的方面,以便ZZ首先跟随xx,rr,nn,aa和ff。我已经尝试了许多基于大量搜索的方法,但到目前为止还没有成功。

library(ggplot2)
library(dplyr)
library(tidyr)

rownum <- 1:6
orgs <- c('ZZ','xx','rr','nn','aa','ff')
levels(orgs) <- rownum

qtd <- c(1216.146, 743.482, 276.105, 135.089, 52.703, 8.767)
commit <- c(2120, 1150, 420.6, 266.1, 244.9, 35.2)
forecast <- c(2150, 1190, 420.79, 266.21, 242.59, 35.19)
plan <- c(2270, 1190, 530.64, 295.11, 211.09, 37.70 )

df <- data.frame( rownum, orgs, qtd, commit, forecast, plan)

df2 <-  data.frame(df[,c('rownum','orgs')], width = 0.1 + 0.9 * ((df$qtd * 2) / sum(df$qtd)), 'commit' = df$qtd/df$commit, 'forecast' = df$qtd/df$forecast, 'plan' = df$qtd/df$plan)
n2 <- ncol(df2)
tg2 <- tbl_df(df2) %>% gather('target','percent',4:n2)

p2 = ggplot(data = tg2, aes(x=target, y = percent * 100, fill=factor(target)))
p2 = p2 + geom_bar(stat='identity', position='identity')  
p2 = p2 + scale_fill_manual(values=c("dodgerblue4", "darkolivegreen4", "darkorchid3", "goldenrod1"),  labels=c("Commit","Forecast","Plan"))
p2 = p2 + labs(fill="Target")
p2 = p2 + facet_grid(.~orgs)
p2 = p2 + theme(axis.text.x=element_text(angle=90,hjust=1,vjust=.5,colour='gray50'), strip.text.y = element_text(size = 18))

p2

1 个答案:

答案 0 :(得分:0)

library(ggplot2)
library(dplyr)
library(tidyr)

rownum <- 1:6
orgs <- c('ZZ','xx','rr','nn','aa','ff')
levels(orgs) <- rownum

qtd <- c(1216.146, 743.482, 276.105, 135.089, 52.703, 8.767)
commit <- c(2120, 1150, 420.6, 266.1, 244.9, 35.2)
forecast <- c(2150, 1190, 420.79, 266.21, 242.59, 35.19)
plan <- c(2270, 1190, 530.64, 295.11, 211.09, 37.70 )

df <- data.frame( rownum, orgs, qtd, commit, forecast, plan)

df2 <-  data.frame(df[,c('rownum','orgs')], width = 0.1 + 0.9 * ((df$qtd * 2) / sum(df$qtd)), 'commit' = df$qtd/df$commit, 'forecast' = df$qtd/df$forecast, 'plan' = df$qtd/df$plan)
n2 <- ncol(df2)
tg2 <- tbl_df(df2) %>% gather('target','percent',4:n2)
tg2$orgs <- factor(tg2$orgs, levels = c('ZZ','xx','rr','nn','aa','ff'))

p2 = ggplot(data = tg2, aes(x=target, y = percent * 100, fill=factor(target)))
p2 = p2 + geom_bar(stat='identity', position='identity')  
p2 = p2 + scale_fill_manual(values=c("dodgerblue4", "darkolivegreen4", "darkorchid3", "goldenrod1"),  labels=c("Commit","Forecast","Plan"))
p2 = p2 + labs(fill="Target")
p2 = p2 + facet_grid(.~orgs)
p2 = p2 + theme(axis.text.x=element_text(angle=90,hjust=1,vjust=.5,colour='gray50'), strip.text.y = element_text(size = 18))

p2

enter image description here