2017-09-23 117 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

相关问题