bgraph <- ggplot(data = data, aes(x = location)) +
geom_bar(aes(fill = success))
success
是一个百分比,它是4个类别的因数,数据集的4个结果都有变化。我可以轻松地分别计算它们,但是由于ggplot
当前已构成,所以它们是由geom_bar(aes(fill=success))
生成的。
data <- as.data.frame(c(1,1,1,1,1,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7))
data[["success"]] <- c("a","b","c","c","d","d","a","b","b","b","c","d","a","b","b","b","c","c","c","d","a","b","c","d","a","b","c","c","d","d","a","b","b","c","d")
names(data) <- c("location","success")
bgraph <- ggplot(data = data, aes(x = location)) +
geom_bar(aes(fill = success))
bgraph
如何获得各个百分比的标签?更具体地说,我希望每个小节有4个单独的百分比。一种分别代表黄色,浅橙色,橙色和红色。 %的总数加起来为1。
如何在location
内创建相对帧并在geom_col()
和geom_text()
中使用相对帧?
# Create summary stats
tots <-
data %>%
group_by(location,success) %>%
summarise(
n = n()
) %>%
mutate(
rel = round(100*n/sum(n)),
)
# Plot
ggplot(data = tots, aes(x = location, y = n)) +
geom_col(aes(fill = fct_rev(success))) + # could only get it with this reversed
geom_text(aes(label = rel), position = position_stack(vjust = 0.5))
[也许可以直接在ggplot
中执行此操作,但是在dplyr
中进行一些预处理,您将能够实现所需的输出。
library(dplyr)
library(ggplot2)
data %>%
count(location, success) %>%
group_by(location) %>%
mutate(n = n/sum(n) * 100) %>%
ggplot() + aes(x = location, n, fill = success,label = paste0(round(n, 2), "%")) +
geom_bar(stat = "identity") +
geom_text(position=position_stack(vjust=0.5))