ggplot2中堆积条上方的总标签

时间:2021-12-02 20:06:40

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

此代码为我生成此错误:eval中的错误(expr,envir,enclos):找不到对象'任务'

Can't I use several data sources for my plot? Or how am I supposed to get a total label as well?

我不能为我的情节使用几个数据源吗?或者我怎么能得到一个完整的标签呢?

1 个解决方案

#1


2  

Try this

尝试这个

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)

#1


2  

Try this

尝试这个

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)