R ggplot2中堆叠条上方的总标签

R ggplot2中堆叠条上方的总标签,r,ggplot2,R,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",

我想构建一个堆叠条形图,每个堆叠的条形图都有标签,条形图上方有一个总标签

我该怎么解决这个问题

请参见此处的示例代码:

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)
库(dplyr)
图书馆(GG2)
种子(19)
df%
总结(总时间=总和(时间))
#密谋
ggplot(数据=df,aes(x=等级,y=时间,填充=任务))+
几何图形栏(stat=“identity”)+
几何图形文本(aes(标签=时间),位置=位置堆栈(vjust=0.5),颜色=“白色”)+
geom_文本(aes(x=类别,y=时间总数+.5,标签=时间总数),数据=总数)
此代码为我生成此错误: eval(expr、envir、enclose)中出错:找不到对象“task”

我的绘图不能使用多个数据源吗?或者我应该如何获得一个总标签呢?

试试这个

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)
试试这个

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)

仅当我按照上述PoGibas代码对数据进行排序时,此代码才有效。但这是一种更好的表达每个对象的数据源的方式,如下所示。谢谢仅当我按照上述PoGibas代码对数据进行排序时,此代码才有效。但这是一种更好的表达每个对象的数据源的方式,如下所示。谢谢