Home > Back-end >  Merging Two Geom_Col Plots
Merging Two Geom_Col Plots

Time:12-16

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.

CodePudding user response:

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"))

CodePudding user response:

Just as a reference: A more hacky approach (which however is only useful if you aren't aware of the just argument as I was (; or if you need perhaps some more flexibility) might be to manually nudge the bar positions which however requires to convert your group variable to a numeric:

library(ggplot2)
library(ggnewscale)

df$group_num <- as.numeric(factor(df$group))

width <- .45
padding <- .01

ggplot(df)  
  geom_col(
    aes(x = group_num - (width   padding) / 2, y = frequency, fill = group),
    width = width
  )  
  scale_fill_manual(values = c("#CCCCCC", "#ABABAB", "#818181"))  
  new_scale_fill()  
  geom_col(
    aes(x = group_num   (width   padding) / 2, y = frequency, fill = names),
    width = width
  )

  • Related