簡體   English   中英

如何在ggplot2的geom_line中顯示百分比?

[英]How do I display percentage in geom_line in 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM