2016-12-07 51 views
0

我试图对齐使用geom_bar获得的不同图。当我逐一运行每个情节时,它运作良好。我得到了我想要的。但是,当我聚集所有的人都为一个多情节,我也总是相同....结合ggplots删除原始图?

需要明确的是:这是第一个情节,这是很好: enter image description here

这里是我,当我结合这两块地块。第一列应该与上面的图相同...: enter image description here

我找不到问题。这是我的脚本:

##### colonne 6 
i=6 
col=compil[,i] 
nom=names(compil[i]) 
maxi = max(col) 
mini = min(col) 

p5 <- ggplot(compil,aes(x=NIVEAU, y=col)) + 
    geom_bar(stat="identity",position = "identity",aes(width=0.85), 
      fill=ifelse(col > 1, rgb(63,202,20, maxColorValue = 255), 
         ifelse (col< -1,rgb(204,0,0, maxColorValue = 255), 
           rgb(160,160,160, maxColorValue=255)))) + 
    geom_hline(yintercept=0,color=rgb(160,160,160, maxColorValue=255))+ 
    coord_flip(ylim=c(-2.5,2.5)) + 
    labs(x="", y="", title= nom) + guides(fill=F) + 
    theme(panel.grid.major=element_blank(), panel.grid.minor.x=element_blank(), 
     panel.background = element_blank(), axis.text.x=element_blank(), 
     axis.ticks = element_blank(),axis.line= element_blank(), 
     plot.margin=unit(c(1,-1,1,-1),"lines"), plot.title = element_text(size=10)) 
print(p5) 

##### colonne 7 
i=7 
col=compil[,i] 
nom=names(compil[i]) 
maxi = max(col) 
mini = min(col) 

p6 <- ggplot(compil,aes(x=NIVEAU, y=col)) + 
    geom_bar(stat="identity",position = "identity",aes(width=0.85), 
      fill=ifelse(col > 1, rgb(63,202,20, maxColorValue = 255), 
         ifelse (col< -1,rgb(204,0,0, maxColorValue = 255), 
           rgb(160,160,160, maxColorValue=255)))) + 
    geom_hline(yintercept=0,color=rgb(160,160,160, maxColorValue=255))+ 
    coord_flip(ylim=c(-2.5,2.5)) + 
    labs(x="", y="", title= nom) + guides(fill=F) + 
    theme(panel.grid.major=element_blank(), panel.grid.minor.x=element_blank(), 
     panel.background = element_blank(), axis.text=element_blank(), 
     axis.ticks = element_blank(),axis.line= element_blank(), 
     plot.margin=unit(c(1,-1,1,-1),"lines"), plot.title = element_text(size=10)) 
print(p6) 

vplayout <- function(x, y) viewport(layout.pos.row = x, layout.pos.col = y) 
grid.newpage() 
pushViewport(viewport(layout = grid.layout(1, 3))) 
print(p5, vp = vplayout(1, 1:2)) 
print(p6, vp = vplayout(1, 3)) 

如果有人能帮我找到这个错误,我真的很感谢!当然,我做错了什么,但什么? 预先感谢您的时间和您的帮助!

+0

这可能是由于'ggplot'的懒惰以及eval你改变同一组值的每个情节,但很难说没有一些示例数据。可能需要重命名'colonne 7'的变量,使得这些名称对于'colonne 6'的名称是唯一的。 – Nate

+0

要测试@NathanDay的建议,请在生成p6后尝试打印p5。 –

+0

我正在考虑做一个循环,这就是为什么我保持同一个名字......但你说得对:我太懒了!通过将所有变量重命名为@Nathan Day说,它现在正在按照预期的方式工作!非常感谢你! – Sandrine

回答

0

TL;博士尝试用aes_string(x="NIVEAU", y = nom, fill = nom),其中nom = names(compil)[i]替换aes(x=NIVEAU, y=col)


col似乎是一个载体,但里面aes()你应该从data.frame通过不带引号的变量。直接传递值会导致惊喜,因为ggplot2在构建图时并不知道在哪里查找“col” - 它正在数据中寻找这样的变量,这些变量绑定到情节环境,而且它不在那里,所以下一步是看在全球环境...

出于同样的原因,fill = ifelse()东西不能按预期工作,应该删除。将颜色映射为值是ggplot2中缩放的工作,因此只需映射fill = nom,然后添加scale_fill_manual(...)或任何其他类型的兼容缩放。

(猜测,因为没有可重复的代码)

+0

感谢@baptiste的评论。我不熟悉“aes”的使用。感谢你,我学到了一些东西! ...不幸的是,它不工作,但我不确定如何使用它......我会进一步推动写一个更好的脚本。 – Sandrine