34

I want to create a side by side barplot using geom_bar() of this data frame,

> dfp1
   value   percent1   percent
1 (18,29] 0.20909091 0.4545455
2 (29,40] 0.23478261 0.5431034
3 (40,51] 0.15492958 0.3661972
4 (51,62] 0.10119048 0.1726190
5 (62,95] 0.05660377 0.1194969

With values on the x-axis and the percents as the side by side barplots. I have tried using this code,

p = ggplot(dfp1, aes(x = value, y= c(percent, percent1)), xlab="Age Group")
p = p + geom_bar(stat="identity", width=.5)  

However, I get this error: Error: Aesthetics must either be length one, or the same length as the dataProblems:value. My percent and percent1 are the same length as value, so I am confused. Thanks for the help.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
Hound
  • 932
  • 2
  • 17
  • 26

2 Answers2

51

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

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • 3
    How can I use the geom_text(aes(x=, y=, label=mylabels) option with dodge bars in order to get a label centered on each bar? – skan Sep 26 '17 at 14:44
5

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

sbha
  • 9,802
  • 2
  • 74
  • 62