ggplot side by side geom_bar()

后端 未结 2 448
深忆病人
深忆病人 2020-12-03 01:38

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         


        
2条回答
  •  天涯浪人
    2020-12-03 01:57

    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

提交回复
热议问题