2017-04-03 1 views
0

을 가장 낮은 가장 높은에서 바의 순서를, 나는 시도ggplot2는 각면에 아래 <code>df</code>에서

각면에서 가장 높은에서 가장 낮은 막대를 다시 정렬 할

df <- df %>% tidyr::gather("var", "value", 2:4) 
ggplot(df, aes (x = reorder(id, -value), y = value, fill = id))+ 
    geom_bar(stat="identity")+facet_wrap(~var, ncol =3) 

그것은했다 나 enter image description here

각 패싯에서 막대를 가장 높은 순서로 정렬하지 않았습니다.

내가 원하는 것을 얻는 다른 방법을 찾았습니다. 그때 grid.arrange()

#I got this function from @eipi10's answer 
#http://stackoverflow.com/questions/38637261/perfectly-align-several-plots/38640937#38640937 
#Function to extract legend 
# https://github.com/hadley/ggplot2/wiki/Share-a-legend-between-two-ggplot2-graphs 
g_legend<-function(a.gplot) { 
    tmp <- ggplot_gtable(ggplot_build(a.gplot)) 
    leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box") 
    legend <- tmp$grobs[[leg]] 
    return(legend) 
} 

p1 <- ggplot(df[df$var== "A", ], aes (x = reorder(id, -value), y = value, fill = id))+ 
    geom_bar(stat="identity") + facet_wrap(~var, ncol =3) 

fin_legend <- g_legend(p1) 
p1 <- p1 + guides(fill= F) 

p2 <- ggplot(df[df$var== "B", ], aes (x = reorder(id, -value), y = value, fill = id))+ 
    geom_bar(stat="identity") + facet_wrap(~var, ncol =3)+guides(fill=FALSE) 

p3 <- ggplot(df[df$var== "C", ], aes (x = reorder(id, -value), y = value, fill = id))+ 
    geom_bar(stat="identity") + facet_wrap(~var, ncol =3)+guides(fill=FALSE) 


grid.arrange(p1, p2, p3, fin_legend, ncol =4, widths = c(1.5, 1.5, 1.5, 0.5)) 

결과를 사용하여 모든 플롯을 결합, 한 번에 각 변수를 음모 나 막대를 주문 도울 수있는 간단한 방법이 있다면 내가 궁금해 enter image description here

를 원하는 것입니다했다 개별 변수를 개별적으로 플롯하지 않고 모든 패싯에서 가장 높은 값에서 가장 낮은 값으로 정렬 한 다음 결합합니다. 어떤 제안이라도 대단히 감사하겠습니다.

데이터

df <- read.table(text = c(" 
id A B C 
site1 10 15 20 
site2 20 10 30 
site3 30 20 25 
site4 40 35 40 
site5 50 30 35"), header = T) 

답변

2

접근법은 아래 facet_wrap()와 X 축에 대한 특별히 준비된 변수를 사용하지만 정확한 X 축 라벨 표시하는 scale_x_discrete()labels 파라미터를 사용

데이터

I 더 유창한있어를 준비를 data.table에 있으므로 여기가 사용됩니다. 데이터 조작을 위해 선호하는 패키지를 자유롭게 사용할 수 있습니다.

편집 : 삭제됨 제 더미 변수 만이 필요 ord

library(data.table) 
# reshape from wide to long 
molten <- melt(setDT(df), id.vars = "id") 
# create dummy var which reflects order when sorted alphabetically 
molten[, ord := sprintf("%02i", frank(molten, variable, -value, ties.method = "first"))] 

molten 
#  id variable value ord 
# 1: site1  A 10 05 
# 2: site2  A 20 04 
# 3: site3  A 30 03 
# 4: site4  A 40 02 
# 5: site5  A 50 01 
# 6: site1  B 15 09 
# 7: site2  B 10 10 
# 8: site3  B 20 08 
# 9: site4  B 35 06 
#10: site5  B 30 07 
#11: site1  C 20 15 
#12: site2  C 30 13 
#13: site3  C 25 14 
#14: site4  C 40 11 
#15: site5  C 35 12 

플롯

library(ggplot2) 
# `ord` is plotted on x-axis instead of `id` 
ggplot(molten, aes(x = ord, y = value, fill = id)) + 
    # geom_col() is replacement for geom_bar(stat = "identity") 
    geom_col() + 
    # independent x-axis scale in each facet, 
    # drop absent factor levels (not the case here) 
    facet_wrap(~ variable, scales = "free_x", drop = TRUE) + 
    # use named character vector to replace x-axis labels 
    scale_x_discrete(labels = molten[, setNames(as.character(id), ord)]) + 
    # replace x-axis title 
    xlab("id") 

enter image description here

에게

df <- read.table(text = " 
id A B C 
site1 10 15 20 
site2 20 10 30 
site3 30 20 25 
site4 40 35 40 
site5 50 30 35", header = T) 
데이터를 작성
+0

시간과 도움에 감사드립니다. – aelwan

+0

코드의 각 줄에 대한 자세한 설명을 정말 고맙게 생각합니다. 많은 분들께 감사드립니다. – aelwan

1

당신이 X 축 레이블을 잃을하고자하는 경우, 당신은 실제 y 값을 사용하여이 작업을 수행 할 수와 X 미적, 각면에 사용되지 않는 요소의 수준을 떨어 뜨리고 :

ggplot(df, aes (x = factor(-value), y = value, fill = id))+ 
    geom_bar(stat="identity", na.rm = TRUE)+ 
    facet_wrap(~var, ncol =3, scales = "free_x", drop = TRUE) + 
    theme(
     axis.text.x = element_blank(), 
     axis.ticks.x = element_blank() 
    ) 

결과 :

enter image description here

x 축 레이블의 손실은 계속 진행할 색상이 있고 (패싯 전체에서 일관성이 없기 때문에 어쨌든 x 축은 혼란 스럽기 때문에) 여기서 너무 나쁘지는 않습니다.

+0

시간과 도움에 감사드립니다 – aelwan

관련 문제