I want to build a stacked bar chart, with labels for each stacked bar and a total label above the bar.
How am I supposed to solve this?
See example code here:
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)
This codes generates this error for me: Error in eval(expr, envir, enclos) : object 'task' not found
Can't I use several data sources for my plot? Or how am I supposed to get a total label as well?