使用R/ggplot2将标签添加到geom_bar()中的各个% [英] Adding labels to individual % inside geom_bar() using R / ggplot2

查看:118
本文介绍了使用R/ggplot2将标签添加到geom_bar()中的各个%的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

bgraph <- ggplot(data = data, aes(x = location)) +
  geom_bar(aes(fill = success))

success是一个百分比,由4个类别的因子计算得出,数据集具有4个结果.我可以轻松地分别计算它们,但是由于ggplot当前已构成,所以它们是由geom_bar(aes(fill=success))生成的.

success is a percentage calculated as a factor of 4 categories with the varying 4 outcomes of the data set. I could separately calculate them easily, but as the ggplot is currently constituted, they are generated by the 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.

How do I get labels over the individual percentages? More specifically, I wanted 4 individual percentages for each bar. One for yellow, light orange, orange, and red, respectively. %'s all add up to 1.

推荐答案

也许可以直接在ggplot中进行此操作,但是通过dplyr中的一些预处理,您将能够实现所需的效果输出.

Maybe there is a way to do this in ggplot directly but with some pre-processing in dplyr, you'll be able to achieve your desired output.

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))

这篇关于使用R/ggplot2将标签添加到geom_bar()中的各个%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆