ggplot2visualizationgeom-col

Merging Two Geom_Col Plots


I have two geom_col graphs and I want to merge each of the bars side by side in one graph.

df<-data.frame(names=c("A","B","C","D","E","F","G","H","I"), frequency=c(0.1,0.7,0.2,0.4,0.4,0.2,0.8,0.1,0.1),group=c("1","2","3","3","2","1","1","2","3"))

p1<- ggplot(df) + geom_col(aes(x=group ,y=frequency, fill=group)) + scale_fill_manual(values=c("#CCCCCC","#ABABAB","#818181"))

p2<- ggplot(df) + geom_col(aes(x=group ,y=frequency, fill=names)) 

I can superimpose these two plots by using:

ggplot(df) + geom_col(aes(x=group ,y=frequency, fill=group)) + scale_fill_manual(values=c("#CCCCCC","#ABABAB","#818181")) +
   new_scale_fill() + geom_col(aes(x=group ,y=frequency, fill=names), width=0.5)

I want to draw them side by side in a way that the first bar of p1 will be together with the first bar of p2, and so on. I overcome the problem of using two scale_fills by using "ggnewscale". However, I can't still merge them.

I will appreciate your help.


Solution

  • You might be best giving each bar an "offset" and reducing width:

    library(ggplot2)
    library(ggnewscale)
    
    df<-data.frame(names=c("A","B","C","D","E","F","G","H","I"), 
                   frequency=c(0.1,0.7,0.2,0.4,0.4,0.2,0.8,0.1,0.1),
                   group=c("1","2","3","3","2","1","1","2","3"))
    
    ggplot(df) +
      geom_col(aes(x = group , y = frequency, fill = names), width = 0.4, just = 0) +
      new_scale_fill() +
      geom_col(aes(x = group , y = frequency, fill = group), width = 0.4, just = 1) +
      scale_fill_manual(values = c("#CCCCCC", "#ABABAB", "#818181"))