简体   繁体   中英

Add sample size to ggplot2 bar plot in R

I'm trying to produce bar graph with ggplot2 in R. Graph is produced perfectly so far but when I try adding sample size, it doesn't work. Here is my code:

library(ggplot2)
library(ggthemes)
library(dplyr)
library(ggsignif)
Demo1 <- demo.csv("demo.csv", header = T, sep = ",")
Demo1
mean <- aggregate(A ~ B, Demo1, mean)
sd <- aggregate(A ~ B, Demo1, sd)
samplesize <- Demo1 %>% group_by(B) %>% summarise(count = n())

X <- ggplot(Demo1, aes(y = B, x = A))
X <- X + stat_summary(fun = "mean", 
                  geom = "bar") 
X <- X + stat_summary(fun = "mean", 
                  geom = "errorbar",
                  fun.min = function(x)mean(x)-sd(x), 
                  fun.max = function(x)mean(x) + sd(x), 
                  width = 0.1,
                  size = 0.5)
X <- X + theme_classic() 

Then, tried to paste samplesize which I calculated in the beginning by following code.

X <- X + geom_text(aes(x = A, y = B, label = samplesize))

Is there any good way to do?

Thanks in advance.

Are you looking for?

library(dplyr)
library(ggplot2)

mtcars %>%
  count(cyl) %>%
  ggplot() + aes(cyl, n, label = n) + 
  geom_col() + geom_text(vjust = -0.5)

在此处输入图像描述


For your data you can try to add -

X + geom_text(data = samplesize, aes(label = count), vjust = -5.5, hjust = -0.5)

Adjust hjust and vjust value according to your choice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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