我试图从一个数据帧,它具有在y轴计数但显示为标签百分比和计数的级联创建中的R的条形图。
我的数据帧看起来如下:
ID Response
1 No
2 Yes
3 No
.. ..
最终的结果我想有将是一个图表,如下一个
这应该让你去:
library(tidyverse)
df %>%
group_by(Response) %>%
summarise(count = n()) %>%
mutate(Label = paste0(count, " - ", round(count / sum(count) * 100, 2), "%")) %>%
ggplot(aes(x = Response, y = count)) +
geom_bar(stat = 'identity', fill = 'lightblue') +
geom_text(aes(label = Label)) +
theme_minimal()
的溶液如上述可以是创建一个Label
柱,然后可以通过在需要时geom_text
。
伪数据帧:
df <- data.frame(
ID = c(1:100),
Response = c(rep("Yes", 60), rep("No", 40))
)
我想尝试像下面。这真棒,你正在使用summarize
和mutate
;我想通过我的习惯有时会使用基础功能,如table
。
library(tidyverse)
resps<-sample(c("yes", "no"), 850, replace=T)
percents<-round(100*table(resps)/length(resps),2)
counts<-as.numeric(table(resps))
plotdat<-data.frame(percents, counts=counts, response=rownames(percents))
plotdat %>% ggplot(aes(response, counts)) +
geom_col()+
geom_text(aes(y=counts+10), label=paste(percents,"% ", counts))
labs(y="respondents")+
theme_classic()
这是从another question一个有用的解决方案上SO:
library(ggplot2)
library(scales)
data.frame(response = sample(c("Yes", "No"), size = 100, replace = T, prob = c(0.4, 0.6))) %>%
ggplot(aes(x = response)) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
geom_text(aes(y = ((..count..)/sum(..count..)),
label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
scale_y_continuous(labels = percent) +
labs(title = "Proportion of Responses", y = "Percent", x = "Response")