2013-05-28 86 views
0

我希望把条形图中的另一条战线(我使用阿尔法传达信息)禁用堆叠GGPLOT2

在GGPLOT2如果我做ggplot() + geom_bar() + geom_bar()我结束了一个堆积条形图,不是一个层中前另一个。如何更改/禁用此功能?

TPlot = ggplot() + 
    geom_bar(aes(x = 1:3, y=c(1,1,1), width=0.1),stat="identity", alpha=0, colour = "red",position="identity") + 
    xlab("x") + 
    ylab("y") 

for (i in 1:3){ 
    TPlot = TPlot + geom_bar(aes(x = 1:3, y = c(i,i,i), width=0.1),stat="identity", position="identity", alpha=0.2) 
} 

TPlot 

我希望看到更黑暗的地区,更多的酒吧被绘制,但事实并非如此。

+3

您设置了'position =“identity”'? – joran

+0

不,这不适合我。我会提供更多的代码,坚持下去。 –

+0

'position =“identity”'正在工作,但其他事情却出错了,可能与你在'aes()'里面做的所有非标准(和不明智)事情有关。 – joran

回答

3

我不明白为什么,但似乎有什么奇怪的与for循环。下面的代码运行良好。但是当我尝试使用for循环时,仅添加了最后的geom_bar

TPlot = ggplot() + 
    geom_bar(aes(x = 1:3, y=c(1,1,1), width=0.1),stat="identity", alpha=0.2, 
      position="identity") + 
    xlab("x") + 
    ylab("y") 

TPlot = TPlot + geom_bar(aes(x = 1:3, y = c(2,2,2), width=0.1), 
         stat="identity", position="identity", alpha=0.2) 
TPlot = TPlot + geom_bar(aes(x = 1:3, y = c(3,3,3), width=0.1), 
         stat="identity", position="identity", alpha=0.2) 

TPlot 

enter image description here

随着for循环。

TPlot = ggplot() + 
    geom_bar(aes(x = 1:3, y=c(1,1,1), width=0.1),stat="identity", alpha=0.2, 
      position="identity") + 
    xlab("x") + 
    ylab("y") 

for (i in 2:3){ 
    TPlot = TPlot + geom_bar(aes(x = 1:3, y = c(i,i,i), width=0.1), 
          stat="identity", position="identity", alpha=0.2) 
} 

TPlot 

enter image description here

此代码的工作。这导致了第一张照片的一张照片。感谢乔兰。

TPlot = ggplot() + 
    geom_bar(aes(x = 1:3, y=c(1,1,1), width=0.1),stat="identity", alpha=0.2, 
      position="identity") + 
    xlab("x") + 
    ylab("y") 

for (i in c(2,3)){ 
    TPlot = TPlot + geom_bar(data=data.frame(x = 1:3, y = c(i,i,i)), 
          aes(x=x, y=y, width=0.1), 
          stat="identity", alpha=0.2) 
} 

TPlot 
+0

啊,我打算增加大约250个地块,所以我需要for循环!任何猜测如何让这个工作? –

+0

@ N.McA。我最好的猜测是,和往常一样,要求ggplot解决不在提供的数据框中的变量名是个坏主意。这就是你用'i'在这里做的事情。关于'for'循环如何被解析的功能性的一些问题是阻止ggplot看到我想的每个单独的'我'值,所以它们都获得最后的值。 – joran

+0

不,但看起来在'for'循环中,最后一个'geom_bar'被绘制了两次,在第一个图表上获得了像'y = 2'一样的较暗的颜色。 – DrDom

3

aes()产生的未计算表达式列表”,根据其帮助页面,所以在你的for循环你结束了,因为它们指向一个变量名“我”,这是不计算是相同的层。当ggplot最终构建图层时,它会使用我周围的任何值(更具体地说,如果给出一个,它可以查看可选的environment)。但这在这里不起作用,因为你需要为每个图层设置不同的i值。您可以在循环中使用substitute()或bquote(),但最好为每个图层构造一个新的data.frame。或者更好的是,用你的循环创建一个单一的data.frame,用一个变量来跟踪它引用的步骤。然后,您可以使用美学绘图和/或刻面,这更符合ggplot2的设计目标(并且比拥有多个独立图层更高效)。