You are on page 1of 1

Barplot with Errorbar (using R programming)

Sharing my codes :)
# install.packages(c("dplyr", "ggplot2", "ggthemes"))
library(dplyr)   # For data manupulation
library(ggplot2)  # For Data Visualization
library(ggthemes)  # For some extra themes & automatic colors
theme_set(theme_bw())  # Setting permanent theme for all graphs
data <- ToothGrowth  
(as_tibble(data)-> data)  
data %>% relocate(dose, supp, len) %>% # relocating the variables
  mutate(dose= as.factor(dose)) %>%
  group_by(dose, supp) %>%
  summarise(length= mean(len), sd= sd(len)) %>% # mean and sd is required for barplot and
errorbar respectively
  ungroup() %>% 
  ggplot(aes(x= dose, y= length, fill= supp)) +
  geom_col(position = position_dodge(.7),
       show.legend = T) + 
  ggthemes::scale_fill_tableau(name= "Suppliment") + 
  geom_errorbar(aes(ymax=length+sd, ymin= length-sd), width= .2,
         position = position_dodge(.7), size= 1.1,
         col= "black") +
  geom_point(position = position_dodge(.7), size=4,
        show.legend = F) +
  labs(title = "Barplot with Errorbar",
     caption = "Data_source: ToothGrowth",
     subtitle = "Study of Medicine on Toothgrowth",
     tag = "Fig 1",
     x= "Dose", y= "Length")

You might also like