2017-02-21 10 views
0

나는 이런 종류의 질문이 이미 제기 된 것을 알고 있지만 이미 그것을 몇 시간 동안 내 데이터 세트에 적용하려고 시도했지만 성공하지는 못했다.누적 막 대형 차트의 그룹 순서와 R의 범례를 변경합니까?

는 여기에 내가 그룹의 순서를 조정하는 두 가지 방법을 시도

> df 
     prot X nr 
1 unmodified same 68 
2  1 Ac same 14 
3  2 Ac same 7 
4  3 Ac same 4 
5  4 Ac same 3 
6  5 Ac same 2 
7  6 Ac same 1 
8  7 Ac same 2 

내 dataframe하지만 두 경우 모두 전설 정확히 역순이다. 전설의 그룹 순서와 음모의 그룹 순서를 어떻게 일치시킬 수 있습니까? way1 : enter image description here

way2 :

y <- read.csv("df.csv",sep=",") #sep=";" 
df <- data.frame(y) 

df$prot <- factor(df$prot, levels = c("7 Ac", "6 Ac", "5 Ac", "4 Ac", "3 Ac", "2 Ac", "1 Ac","unmodified")) #order groups 

df <- ddply(df, .(X), 
     transform, pos = cumsum(nr) - (0.5 * nr)) #adjust the position of the data labels:create new variable at the centre of each bar 

p<-ggplot(data=df, aes(x=X, y=nr, fill=prot)) + 
geom_bar(stat="identity", position=position_stack(), width=0.2, colour="gray")+ # stacked, bar-width, outline-colour = colour 
theme(panel.background = element_rect(fill = "ivory" , colour="ivory"))+ #backgroundcolor 
coord_flip()+ 
theme(legend.position="bottom") + 
guides(fill = guide_legend(nrow = 1)) + 
geom_text(data=df, aes(x = X, y = pos, label = paste0(nr,"%")), 
     size=4) 

p 

p 

나에게이 결과 제공 : 당신은 단지에 reverse 매개 변수를 사용해야합니다 enter image description here

답변

0

y <- read.csv("df.csv",sep=",") #sep=";" 
df <- data.frame(y) 

df$prot <- factor(df$prot, levels = rev(df$prot)) #order groups 

p<-ggplot(df, aes(x=X, y=nr, fill=prot)) + 
geom_bar(stat="identity", position=position_stack(), width=0.2, colour="gray", aes(fill = prot))+ # stacked, bar-width, outline-colour = colour 
theme(panel.background = element_rect(fill = "ivory" , colour="ivory"))+ 
coord_flip()+ 
theme(legend.position="bottom") + 
guides(fill = guide_legend(nrow = 1)) + 
geom_text(aes(label=nr), color="black",vjust = -3, position = position_stack()) # add labels (%) non-overlapping 

p 

것은 나에게이 결과를 제공 guide_legend 및 설정 예 : TRUE,

df<- data.frame(prot = c("unmodified", paste(1:7, "AC")), X = rep("same", 8), 
        nr = c(68,14,7,4,3,2,1,2)) 

library(ggplot2) 

df$prot <- factor(df$prot, levels = rev(df$prot)) #order groups 

p<-ggplot(df, aes(x=X, y=nr, fill=prot)) + 
     geom_bar(stat="identity", position=position_stack(), width=0.2, colour="gray", aes(fill = prot))+ # stacked, bar-width, outline-colour = colour 
     theme(panel.background = element_rect(fill = "ivory" , colour="ivory"))+ 
     coord_flip()+ 
     theme(legend.position="bottom") + 
     # to change ordering of legend, set reverse = TRUE 
     guides(fill = guide_legend(nrow = 1, reverse = TRUE)) + 
     geom_text(aes(label=nr), color="black",vjust = -3, position = position_stack()) # add labels (%) non-overlapping 

p