Ggplot side by side geom_bar ()

I want to create side by side 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 ​​along the x axis and percentages as side by side. I 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 be either the same or the same length as dataProblems: value. My interest and interest 1 are the same length as the cost, so I'm confused. Thanks for the help.

+8
r ggplot2
source share
1 answer

You need to melt your data first value . By default, another variable will be created called value , so you will need to rename it (I named it percent ). Then build a new dataset with fill to divide the data into groups, and position = "dodge" to arrange the columns side by side (rather than one above the 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

+17
source share

All Articles