Pablo
Pablo

Reputation: 89

Overlapping bars when trying to fix bar width using facet_wrap from ggplot2

I have the same problem which is explained here Bars in geom_bar have unwanted different widths when using facet_wrap That is, when facetting my bars show a different width. I have tried the solution proposed there, but it seems I'm doing something wrong because then my bars overlap. I'm not an advanced R user, so any explanation would be much appreciate.

My code:

# Data
z <- rbind.data.frame(c(23.230077, 109.824940, 72.313763, 76.95888), 
                  c(29.154963, 113.716729, 94.689684, 64.29041),
                  c(8.450325, 99.190459, 53.193431, 32.97232),
                  c(15.719120, 126.947621, 39.767791, 56.8059),
                  c(15.497960, 117.942545, 73.659386, 69.37012),
                  c(13.522866, 9.939251, 5.906541, 27.69283))
colnames(z) <- c("Biomass", "Metals", "Other minerals", "Fossil fuels")
rownames(z) <- c("Exiobase full", "Exiobase global", "Exiobase EU","ENVIMAT", "ENVIMAT corrected", "Direct Imports")
library(ggplot2)
library(reshape2)
library(plyr)

z1 <- melt(as.matrix(z)); z2 <- c(rep(c(rep("Exiobase", 3), rep("Envimat",2), "Direct"),4))
z3 <- cbind.data.frame(z1, z2)
colnames(z3) <- c("Model", "Material", "Value", "Version")

# Here from the solution posted
N <- ddply(z3, .(Version), function(x) length(row.names(x)))
N$Fac <- N$V1 / max(N$V1)
z4 <-  merge(z3, N[,-2], by = c("Version"))

# Plotting
fig3 <- ggplot(data=z4, aes(x=Version, y=Value ,fill=Model))+
    geom_bar(aes(width = 1.5*Fac),stat="identity", position=position_dodge())+  scale_fill_brewer(palette="Set2")+ ylab("Million Tons")+
    geom_text(aes(label = sprintf("%.1f",round(Value, 1), size=10)), position=position_dodge(width=0.9), vjust=-0.25)+
    theme_bw()+theme(panel.grid.major.x = element_blank(), panel.grid.major.y = element_line(colour="grey", linetype = "dotted"),axis.title.x = element_blank(),legend.title=element_blank(), panel.background = element_rect(colour = "black"),legend.key=element_blank(),legend.text = element_text(colour="black"), strip.background = element_blank())+
    facet_wrap(~Material, nrow=2)
plot(fig3)

Many thanks!

Then if I use BarWidth and DodgeWith as proposed as an answer to my original question, I can't control dodge width for group of bars. That is, I would like to keep some of them together as shown below for the two bars "Envimat". I have changed colours so two purple bars and three red-orange bars should remain together. The new code:

BarWidth = 0.75
DodgeWidth = .5
fig3 <- ggplot(data=z4, aes(x=Version, y=Value ,fill=Model))+
    geom_bar(aes(width = BarWidth*Fac),stat="identity", position=position_dodge(width = DodgeWidth))+  
    ylab("Million Tons")+
    geom_text(aes(label = sprintf("%.1f",round(Value, 1))), size=2, 
              position=position_dodge(width=DodgeWidth), vjust=-0.25)+
    scale_fill_manual(values=c("#fdcc8a", "#fc8d59", "#d7301f", "#b3cde3","#8c96c6", "#c2e699"))+
    theme_bw()+theme(panel.grid.major.x = element_blank(), 
                     panel.grid.major.y = element_line(colour="grey", linetype = "dotted"),
                     axis.title.x = element_blank(),legend.title=element_blank(), 
                     panel.background = element_rect(colour = "black"),
                     legend.key=element_blank(),
                     legend.text = element_text(colour="black"), 
                     strip.background = element_blank())+
    facet_wrap(~Material, nrow=2)
plot(fig3)

Now the problem (in the red-orange bars, I would like to control distance between green and purple bars): red-orange bars overlapped

If I fix the problem for the red-orange bars, purple ones are separated

BarWidth = 0.75
DodgeWidth = .75

Thanks a lot

Upvotes: 3

Views: 966

Answers (1)

Sandy Muspratt
Sandy Muspratt

Reputation: 32874

position_dodge() can take a width parameter. Use it to set the dodging width, and be sure to apply it to both geom_bar and to geom_text. You will probably need to adjust the limits of the y axis scale, the size of the text, and maybe the size of the graphics device.

Also, take size outside the aes() statement in geom_text.

Something like this:

# Data
z <- rbind.data.frame(c(23.230077, 109.824940, 72.313763, 76.95888), 
                  c(29.154963, 113.716729, 94.689684, 64.29041),
                  c(8.450325, 99.190459, 53.193431, 32.97232),
                  c(15.719120, 126.947621, 39.767791, 56.8059),
                  c(15.497960, 117.942545, 73.659386, 69.37012),
                  c(13.522866, 9.939251, 5.906541, 27.69283))
colnames(z) <- c("Biomass", "Metals", "Other minerals", "Fossil fuels")
rownames(z) <- c("Exiobase full", "Exiobase global", "Exiobase EU","ENVIMAT", "ENVIMAT corrected", "Direct Imports")
library(ggplot2)
library(reshape2)
library(plyr)

z1 <- melt(as.matrix(z)); z2 <- c(rep(c(rep("Exiobase", 3), rep("Envimat",2), "Direct"),4))
z3 <- cbind.data.frame(z1, z2)
colnames(z3) <- c("Model", "Material", "Value", "Version")

# Here from the solution posted
N <- ddply(z3, .(Version), function(x) length(row.names(x)))
N$Fac <- N$V1 / max(N$V1)
z4 <-  merge(z3, N[,-2], by = c("Version"))

# Plotting
BarWidth = .75
DodgeWidth = .75
fig3 <- ggplot(data=z4, aes(x=Version, y=Value ,fill=Model))+
    geom_bar(aes(width = BarWidth*Fac),stat="identity", position=position_dodge(width = DodgeWidth))+  
   scale_fill_brewer(palette="Set2")+ ylab("Million Tons")+
    geom_text(aes(label = sprintf("%.1f",round(Value, 1))), size=2, 
        position=position_dodge(width=DodgeWidth), vjust=-0.25)+
    theme_bw()+theme(panel.grid.major.x = element_blank(), 
    panel.grid.major.y = element_line(colour="grey", linetype = "dotted"),
     axis.title.x = element_blank(),legend.title=element_blank(), 
    panel.background = element_rect(colour = "black"),
    legend.key=element_blank(),
    legend.text = element_text(colour="black"), 
    strip.background = element_blank())+
    facet_wrap(~Material, nrow=2)
plot(fig3)

enter image description here

EDIT: Revised question

Not a general solution - Solution is specific to fig3

gb <- ggplot_build(fig3)

w = with(gb$data[[1]][1,], xmax-xmin)

for(i in 1:2) {
gb$data[[i]][gb$data[[i]]$group == 2, "x"] = 2-(w/2)
gb$data[[i]][gb$data[[i]]$group == 2, "xmin"] = 2-(w/2)-(w/2)
gb$data[[i]][gb$data[[i]]$group == 2, "xmax"] = 2-(w/2)+(w/2)

gb$data[[i]][gb$data[[i]]$group == 3, "x"] = 2+(w/2)
gb$data[[i]][gb$data[[i]]$group == 3, "xmin"] = 2+(w/2)-(w/2)
gb$data[[i]][gb$data[[i]]$group == 3, "xmax"] = 2+(w/2)+(w/2)
}

# Get the ggplot grob
gp = ggplot_gtable(gb)

library(grid)
grid.newpage()
grid.draw(gp)

enter image description here

Upvotes: 2

Related Questions