Home > Software engineering >  How to overlay individual data points in my barplot
How to overlay individual data points in my barplot

Time:02-15

I want to print individual data points in each of my bars of barplot respectively. Where each bar is the mean of that category

I want this output:

enter image description here

My dataset looks like this which I am importing from an excel sheet

#  A  B  C  D  E
1  3  3  2  2  2
2  NA 2 NA  3  1
3  1  3  3  1  1
library(readxl)
library(ggplot2)
Book1 <- read_excel("C:/Users/helix/Desktop/Book1.xlsx")

x_row = names(Book1)
y_val = colMeans(Book1, na.rm = TRUE)
sd_val = sapply(Book1, sd, na.rm = TRUE)
df = data.frame(x_name = x_row, mean=y_val, sd = sd_val)

ggplot(df, aes(x= x_row, y = y_val ))   
  geom_bar(stat = 'identity') 
  geom_errorbar(aes(ymin=mean-sd, ymax=mean sd), width=.2)

CodePudding user response:

You can add the Book1 dataset to the ggplot command by pivoting it first and then use geom_point:

Book1 <- pivot_longer(Book1, cols = everything())

ggplot()   
  geom_bar(aes(x= x_row, y = y_val), df, stat = 'identity')  
  geom_errorbar(aes(x = x_row, ymin=mean-sd, ymax=mean sd), df, width=.2)  
  geom_point(aes(x = name, y = value, color = name), Book1, size = 5)

enter image description here

data

df <- read.table(header = T, text = "id  A  B  C  D  E
1  3  3  2  2  2
2  NA 2 NA  3  1
3  1  3  3  1  1")
Book1 <- df[,-1]
x_row = names(Book1)
y_val = colMeans(Book1, na.rm = TRUE)
sd_val = sapply(Book1, sd, na.rm = TRUE)
df = data.frame(x_name = x_row, mean=y_val, sd = sd_val)

CodePudding user response:

[![library(tidyverse)
Book1<- data.frame(A= c(3, NA, 1),
                B= c(3,2, 3),
                C= c(2, NA, 3),
                D= c(2, 3, 1),
                E= c(2, 1, 1)
                ) 

x_row = names(Book1)
y_val = colMeans(Book1, na.rm = TRUE)
sd_val = sapply(Book1, sd, na.rm = TRUE)
df = data.frame(x_name = x_row, mean=y_val, sd = sd_val)

round(df$mean, digits = 2)-> df$mean


ggplot(df, aes(x= x_row, y = y_val,fill = x_row ))   
 geom_bar(stat = 'identity') 
 geom_errorbar(aes(ymin=mean-sd, ymax=mean sd), width=.2) 
 geom_text(aes(label = mean), vjust = -0.4, hjust= -0.2)][1]][1]
  • Related