gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:16:43 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com