2014-11-11 7 views
1

ggplot2에서 누적 막대 그래프를 생성합니다. 두 가지 질문이 있습니다 :누적 막대 그래프 위에 총계 추가

y 축 및 데이터 레이블의 배율을 1 대신 1000 단위로 표시하려면 어떻게 변경합니까? 카운트 합계를 각 막대 위에 표시 할 수있는 방법이 있습니까? 예 : 막대 1 위에 굵게 표시 94 (천), 막대 2 위에 122 (천) 표시).

library(ggplot2) 
library(dplyr) 

#Creating the dataset 
my.data <- data.frame(dates = c("1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014"), 
         fruits=c("apple", "orange", "pear", "berries", "watermelon", "apple", "orange", "pear", "berries", "watermelon"), 
         count=c(20000, 30000, 40000, 2000, 2000, 30000, 40000, 50000, 1000, 1000)) 

#Creating a positon for the data labels 
my.data <- 
     my.data %>% 
     group_by(dates) %>% 
     mutate(pos=cumsum(count)-0.5*count) 

#Plotting the data 
ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+  
     geom_bar(stat="identity")+ 
     geom_text(data=subset(my.data, count>10000), aes(y=pos, label=count), size=4) 

답변

2

여기 플롯을 만드는 방법이 있습니다. 먼저 count의 합계를 dates으로 그룹화합니다.

sum_count <- 
    my.data %>% 
    group_by(dates) %>% 
    summarise(max_pos = sum(count)) 

이 새로운 데이터 프레임은 막대 상단에 합계를 표시하는 데 사용할 수 있습니다. (1000)의 단위로 y 축 (1000)을 변경하면

ggplot(data = my.data, aes(x = dates, y = count/1000))+  
    geom_bar(stat = "identity", aes(fill = fruits))+ 
    geom_text(data = subset(my.data, count > 10000), 
      aes(y = pos/1000, label = count/1000), size = 4) + 
    geom_text(data = sum_count, 
      aes(y = max_pos/1000, label = max_pos/1000), size = 4, 
      vjust = -0.5) 

enter image description here

하여 값을 분할함으로써 달성된다
관련 문제