2013-05-28 82 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的設計目標(並且比擁有多個獨立圖層更高效)。