2017-09-23 108 views
0

我想建立一個堆疊酒吧圖表,每個堆疊酒吧的標籤和酒吧上方的總標籤。ggplot2中堆疊酒吧上方的標籤總數

我該如何解決這個問題?

見示例代碼瀏覽:

library(dplyr) 
library(ggplot2) 
set.seed(19) 
df <- data.frame(class = rep(c("Math", "History", "Language"), 5), 
       task = rep(c("Reading", "Lecture", "Exercises", "Seminar", "Exam"), 3), 
       time = sample(1:6, size = 15, replace = TRUE)) 

total <- df %>% 
    group_by(class) %>% 
    summarise(time_total = sum(time)) 

# Plot 
ggplot(data = df, aes(x = class, y = time, fill = task)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label = time), position = position_stack(vjust = 0.5), colour = "white") + 
    geom_text(aes(x = class, y = time_total + .5, label = time_total), data = total) 

此代碼生成此錯誤對我來說:在EVAL 錯誤(表達式,ENVIR,enclos):對象 '任務' 未找到

我不能爲我的情節使用幾個數據源?或者我該如何獲得一個總標籤呢?

回答

1

嘗試此

ggplot() + 
geom_bar(data = df, aes(x = class, y = time, fill = task), stat = "identity") + 
geom_text(data = df, aes(x = class, y = time, label = time), position = position_stack(vjust = 0.5), colour = "white") + 
geom_text(aes(x = class, y = time_total + .5, label = time_total), data = total) 
+0

此代碼只能如果我命令將數據作爲根據上述PoGibas代碼。但這是爲每個對象表達數據源的更好方式。謝謝! – henkar91