【问题标题】:Overlapping bars when trying to fix bar width using facet_wrap from ggplot2尝试使用 ggplot2 中的 facet_wrap 修复条形宽度时重叠条形
【发布时间】:2016-10-04 02:47:46
【问题描述】:

我有同样的问题,这里解释了Bars in geom_bar have unwanted different widths when using facet_wrap 也就是说,在刻面时,我的条形显示不同的宽度。我已经尝试过那里提出的解决方案,但似乎我做错了,因为我的条形重叠。我不是高级 R 用户,所以任何解释都将不胜感激。

我的代码:

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

非常感谢!

然后,如果我按照建议使用 BarWidth 和 DodgeWith 作为对原始问题的回答,我将无法控制条形组的闪避宽度。也就是说,我想将它们中的一些保持在一起,如下所示的两个“Envimat”栏。我改变了颜色,所以两个紫色条和三个红橙色条应该保持在一起。 新代码:

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)

现在的问题(在红橙色条中,我想控制绿色和紫色条之间的距离): red-orange bars overlapped

如果我解决了红橙色条的问题,紫色条会被分开

BarWidth = 0.75
DodgeWidth = .75

非常感谢

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    position_dodge() 可以带宽度参数。使用它来设置闪避宽度,并确保将其应用于geom_bargeom_text。您可能需要调整 y 轴刻度的限制、文本的大小以及图形设备的大小。

    另外,将size 放在geom_text 中的aes() 语句之外。

    类似这样的:

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

    编辑:修改后的问题

    不是通用解决方案 - 解决方案特定于 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)
    

    【讨论】:

    • 谢谢桑迪。我已经使用了您的解决方案,但出现了另一个问题。我想控制条形组(两个用于envimat,三个用于Envimat),以便在更改闪避宽度时它们保持在一起(我将编辑问题)
    • @Pablo 我添加了一个特定于fig3 的编辑。该解决方案修改了ggplot_build 数据中条形的位置。它所做的只是修改两个Envimat 柱的位置。需要一个更通用的解决方案,但我需要一些时间来弄清楚。与此同时,如果有人提出了一个通用的解决方案,那就太好了。