简体   繁体   English

如何使用ggplot2在R中的geom_bar r上放置标签/频率

[英]How to put labels/frequencies over geom_bar r in R with ggplot2

there. 那里。 So, this is my code: 所以,这是我的代码:

library(ggplot2); library(scales); library(reshape2);
da1 <- read.table(text = "NÃO SIM
5 1
24 44
",sep = "",header = TRUE)
da1m <- melt(cbind(da1, ind = rownames(da1)), id.vars = c('ind'))
da1m$Resposta <- c( "NÃO", "SIM", "NÃO", "SIM" )
names(da1m) <- c("Resposta", "variable", "value")

ggplot(da1m,aes(x = variable, y = value,fill = Resposta)) + 
geom_bar(position = "fill",stat = "identity", colour = "black") + 
scale_y_continuous(labels = percent_format())+
labs(title = "Gráfico 1", x="Gosta de utilizar o R", 
    y="Há interessse em aprimorar os conhecimentos em R")+
scale_fill_manual(values=c("#E69F00", "#56B4E9"))+
geom_text(aes(label=value), position=position_dodge(width=0.9), 
        vjust=-0.5)

And this is what I get: 这就是我得到的:

geom_bar with label error 带有标签错误的geom_bar

What am I doing wrong? 我究竟做错了什么? The chart is strangely starting to be also in function of the geom_text when I try to add the frequencies. 当我尝试添加频率时,图表开始奇怪地也开始使用geom_text功能。

For illustration, here are two different options for positioning text labels, but you can alter these as needed: 为了说明起见,这里有两个用于放置文本标签的不同选项,但是您可以根据需要更改它们:

library(dplyr)

# Add two position locations for text labels (centered and top)
da1m = da1m %>% group_by(variable) %>%
  mutate(y.pos.ctr = cumsum(value) - 0.5*value,
         y.pos.top = cumsum(value))

ggplot(da1m, aes(x=variable, y=value, fill=Resposta)) + 
  geom_bar(stat = "identity", colour = "black") +  # get rid of position="fill"
  #scale_y_continuous(labels = percent_format()) +  # y values don't seem to be percentages
  labs(title = "Gráfico 1", x="Gosta de utilizar o R", 
       y="Há interessse em aprimorar os conhecimentos em R")+
  scale_fill_manual(values=c("#E69F00", "#56B4E9")) +
  geom_text(aes(label=value, y=y.pos.ctr), colour="white") +  # Centered value labels
  geom_text(aes(label=value, y=y.pos.top), colour="red")    # Value labels at top of each bar section

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM