我想构建一个堆积条形图,每个堆叠条形图标签和条形图上方的总标签。
我该怎么解决这个问题?
请参阅此处的示例代码:
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中的错误(expr,envir,enclos):找不到对象'任务'
我的情节不能使用多个数据源吗?或者我怎么能得到一个完整的标签呢?
答案 0 :(得分:2)
试试这个
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)