ggplot条形图:如何在y轴上显示百分比

时间:2020-04-12 11:20:13

标签: r ggplot2

我是R的新手,正尝试用我的数据创建一些有意义的条形图。以下是一些使用ggplot2的简单条形图的示例代码:

library(ggplot2)

#a variable with 4 different levels
category <- as.factor(c(1, 2, 3, 3, 2, 2, 1, 2, 4, 4, 1, 3, 2, 2, 2, 1))
#a variable with either 0 ("false") or 1 ("true")
quality <- as.factor(c(0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1))
mydata <- data.frame(category, quality)

plot1 <- ggplot(mydata, aes(x= category, fill=quality)) +
  geom_bar(width=0.25) +
  ggtitle("example") +
  xlab("category") +
  ylab("count") +
  labs("true")
plot1

到目前为止,我只知道如何创建在y轴上具有计数(n)的条形图,并且该条形图基于true的实例数来填充。但是,我需要每个类别中true的实例的百分比。例如:有4个属于类别1的实例,其中3个被标记为true。我需要y轴来显示百分比,在类别1的情况下为75.0%。对于类别2,应为2/7 * 100 = 28,6%

希望这种解释有意义,有人可以提出解决方案!预先谢谢你。

编辑

我对代码做了一些改进,但是现在我面临一个新问题。感觉答案应该很明显,但我无法弄清楚:

category <- as.factor(c(1, 2, 3, 3, 2, 2, 1, 2, 4, 4, 1, 3, 2, 2, 2, 1))
quality <- as.factor(c(0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1))
mydata <- data.frame(category, quality)

mydata<- mydata %>% group_by(category,quality) %>% mutate(count_q = n()) %>% ungroup() %>%
  group_by(category) %>% mutate(tot_q=n(),pc=count_q*100/tot_q)  %>% unique() %>% arrange(category)

plot1 <- ggplot(mydata, aes(x= category, y = pc)) +
  geom_bar(position = 'dodge', stat='identity', fill="red") +
  geom_text(aes(label=round(tot_q)), position=position_dodge(0.9), vjust=-0.5) +
  ggtitle("example") +
  xlab("category") +
  ylab("count")
plot1

由于某种原因,这使我在条形图的顶部两次获得了tot_q值。那么如何删除多余的值?

enter image description here

2 个答案:

答案 0 :(得分:3)

这是使用dplyr

的一种方法

设置library并生成数据

library(ggplot2)
library(dplyr)
#a variable with 4 different levels
category <- as.factor(c(1, 2, 3, 3, 2, 2, 1, 2, 4, 4, 1, 3, 2, 2, 2, 1))
#a variable with either 0 ("false") or 1 ("true")
quality <- as.factor(c(0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1))
mydata <- data.frame(category, quality)
#

使用pc来计算dplyr百分比变量

mydata<- mydata %>% group_by(category,quality) %>% mutate(count_q = n()) %>% ungroup() %>%
  group_by(category) %>% mutate(tot_q=n(),pc=count_q*100/tot_q)  %>% unique() %>% arrange(category)

生成图,将一次校正从y = quality更改为y = count_q

plot1 <- ggplot(mydata, aes(x= category, y = count_q, fill=quality)) +
  geom_bar(position = 'dodge', stat='identity') +
  geom_text(aes(label=round(pc,digits=1)), position=position_dodge(width=0.9), vjust=-0.25) +
  ggtitle("example") +
  xlab("category") +
  ylab("count") +
  labs("true")
plot1

Output plot

答案 1 :(得分:0)

@ sachin2014展示了一个很好的预处理数据的例子。但是我们也可以使用ggplot2中的特殊变量来做同样的事情。

我们可以使用tapply来获取每个sum的{​​{1}}中的..count..个。因为我们在主..x..中定义了..x..,所以它是每个类别。

aes()

enter image description here