r - 如何在 ggplot2 的 geom_line 中显示百分比?

标签 r ggplot2

我正在尝试使用 geom_line 和 geom_point 在 ggplot2 中显示百分比。 我的代码是:

print(ggplot(data=dfComb, aes(x=hour_adj, y=(..count..)/sum(..count..), group=word)) +
        geom_line(aes(colour=dfComb$word)) +
        geom_point(aes(colour=dfComb$word))
      +   ggtitle(paste("Hourly Frequencies of Tweets")) +
        xlab("Hour of Day") +
        ylab("Count") +
        scale_colour_discrete("Word", breaks=c("A","B"), labels=c("yid", "abbo")) +
        scale_y_continuous(labels = scales::percent)
        )

这个错误:

Error in FUN(X[[i]], ...) : object 'count' not found

因为 ..count.. 变量仅由 geom_histogram(我认为!)而非 geom_line 创建。 有没有一种简单的方法可以将百分比与 geom_line 一起使用?

仅供引用:编辑,我的数据是:

dput(dfComb)
structure(list(hour_adj = c(0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 
9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 
22L, 23L, 0L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
13L, 14L, 15L, 16L, 17L, 18L, 19L, 20L, 21L, 22L, 23L), count = c(44, 
24, 22, 36, 26, 18, 39, 35, 50, 46, 46, 41, 57, 49, 34, 56, 54, 
54, 49, 45, 36, 49, 43, 47, 35, 20, 18, 10, 10, 25, 25, 26, 32, 
25, 29, 39, 37, 45, 52, 43, 46, 67, 38, 69, 108, 80, 73, 48), 
    word = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("A", "B"), class = "factor")), .Names = c("hour_adj", 
"count", "word"), row.names = c(NA, -48L), class = "data.frame")

最佳答案

您可以先计算数据框中的百分比。

此外,根据 Roman Lustrik 的评论,最好从 aes() 中按名称调用变量。

library(dplyr)

# sample data
set.seed(1)
dfComb <- data.frame(hour_adj = rep(0:4, 2),
                     count = sample(10:50, 10, replace = T),
                     word = c(rep("A", 5), rep("B", 5)))

ggplot(dfComb %>%
         group_by(word) %>%
         mutate(perc = count/sum(count)) %>%
         ungroup(), 
       aes(x=hour_adj, y=perc, group=word, colour = word)) +
  geom_line() +
  geom_point() + 
  ggtitle(paste("Hourly Frequencies of Tweets")) +
  xlab("Hour of Day") +
  ylab("Count") +
  scale_colour_discrete("Word", breaks=c("A","B"), labels=c("yid", "abbo")) +
  scale_y_continuous(labels = scales::percent)

ggplot

关于r - 如何在 ggplot2 的 geom_line 中显示百分比?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46021262/

相关文章:

使用 R 中的条件从列表中的每个数据框中删除行

r - ggplot 主题格式可以保存为对象吗?

r - 在ggplot2中更改颜色填充顺序

r - 如何获取ggplot图的单轴内具有不同颜色的轴刻度标签?

r - 在 R 中创建具有专业外观的 Powerpoint

python - 在MacOS上安装rpy2

在 R 中运行包含求和的非线性 (nls) 回归

r - ggplot2:geom_ribbon,alpha 取决于每个 x 沿 y 轴的数据密度

r - 使用 grid.arrange 和 ggplot 调整图例大小的问题

R - 在 ggplot2 (geom_col) 中更改形状图例