【问题标题】:Total label above stacked bar in ggplot2ggplot2中堆叠条上方的总标签
【发布时间】:2017-09-23 14:19:55
【问题描述】:

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

我应该如何解决这个问题?

在此处查看示例代码:

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):找不到对象“任务”

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

【问题讨论】:

    标签: r ggplot2


    【解决方案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)
    

    【讨论】:

    • 此代码仅在我按照上面的 PoGibas 代码订购数据时才有效。但这是一种更好的方式来表达每个对象的数据源,就像这样。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 2022-01-23
    • 2020-09-07
    • 1970-01-01
    • 2014-08-30
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多