ggplot side by side geom_bar()

You will need to melt your data first over value. It will create another variable called value by default, so you will need to renames it (I called it percent). Then, plot the new data set using fill in order to separate the data into groups, and position = "dodge" in order put the bars side by side (instead of on top of each other)

library(reshape2)
library(ggplot2)
dfp1 <- melt(dfp1)
names(dfp1)[3] <- "percent"
ggplot(dfp1, aes(x = value, y= percent, fill = variable), xlab="Age Group") +
   geom_bar(stat="identity", width=.5, position = "dodge")  

enter image description here


Similar to David's answer, here is a tidyverse option using tidyr::pivot_longer to reshape the data before plotting:

library(tidyverse)

dfp1 %>% 
  pivot_longer(-value, names_to = "variable", values_to = "percent") %>% 
  ggplot(aes(x = value, y = percent, fill = variable), xlab="Age Group") + 
  geom_bar(stat = "identity", position = "dodge", width = 0.5)

enter image description here

Tags:

R

Ggplot2