ggplot side by side geom_bar()

后端 未结 2 445
深忆病人
深忆病人 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

    0 讨论(0)
  • 2020-12-03 02:00

    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)
    

    0 讨论(0)
提交回复
热议问题