我是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值。那么如何删除多余的值?
答案 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
答案 1 :(得分:0)