2012-08-07 28 views
24

我有數據可以看到兩種不同物種的單養和混合養殖之間的增長差異。此外,我製作了一張圖表,以清晰顯示我的數據。如何爲小平面添加不同的線條

我想要一個有錯誤條的barplot,整個數據集當然會更大,但是對於這個圖,這是帶有barplot的手段的data.frame

plant   species  means 
Mixed culture Elytrigia 0.886625 
Monoculture  Elytrigia 1.022667 
Monoculture  Festuca  0.314375 
Mixed culture Festuca  0.078125 

有了這個數據I中ggplot2,其中plant是在x軸和means在y軸作出的曲線圖,我使用的小面來劃分種類。

這是我的代碼:

limits <- aes(ymax = meansS$means + eS$se, ymin=meansS$means - eS$se) 
    dodge <- position_dodge(width=0.9) 

    myplot <- ggplot(data=meansS, aes(x=plant, y=means, fill=plant)) + facet_grid(. ~ species) 
    myplot <- myplot + geom_bar(position=dodge) + geom_errorbar(limits, position=dodge, width=0.25) 
    myplot <- myplot + scale_fill_manual(values=c("#6495ED","#FF7F50")) 
    myplot <- myplot + labs(x = "Plant treatment", y = "Shoot biomass (gr)") 
    myplot <- myplot + opts(title="Plant competition") 
    myplot <- myplot + opts(legend.position = "none") 
    myplot <- myplot + opts(panel.grid.minor=theme_blank(), panel.grid.major=theme_blank()) 

到目前爲止,這是罰款。但是,我想在兩個方面添加兩條不同的水平線。對於這一點,我用這個代碼:

hline.data <- data.frame(z = c(0.511,0.157), species = c("Elytrigia","Festuca")) 
    myplot <- myplot + geom_hline(aes(yintercept = z), hline.data) 

但是,如果我這樣做,我得到一個情節是有兩個額外的方面,其中兩條水平線繪製。相反,我希望水平線被繪製在帶有橫條的小平面上,而不是創造出兩個新的方面。任何人都知道如何解決這個問題。

我想有更清楚,如果我把這個圖我現在創建:

enter image description here

+0

是'abline'你在找什麼? – Pop 2012-08-07 12:51:36

+0

不,我只需要一個水平線,在給定的y座標。然而,每個方面的價值都不相同,例如Elytrigia的水平線爲0.511,Festuca的水平線爲0.157。 – Marinka 2012-08-07 12:55:45

+3

我可以建議你完全按照從控制檯上剪切和粘貼你的數據集,或者使用'dput(means)'給我們提供你的數據。 – 2012-08-07 12:56:10

回答

45

確保易變的種類是在這兩個數據集是相同的。如果在一個對他們的一個因素,那麼它必須是一個因素,在其他太

library(ggplot2) 
dummy1 <- expand.grid(X = factor(c("A", "B")), Y = rnorm(10)) 
dummy1$D <- rnorm(nrow(dummy1)) 
dummy2 <- data.frame(X = c("A", "B"), Z = c(1, 0)) 
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) + 
    geom_hline(data = dummy2, aes(yintercept = Z)) 

enter image description here

dummy2$X <- factor(dummy2$X) 
ggplot(dummy1, aes(x = D, y = Y)) + geom_point() + facet_grid(~X) + 
    geom_hline(data = dummy2, aes(yintercept = Z)) 

enter image description here

+0

哦,是的,現在我記得我的物種名稱背後有一個空間,多麼討厭。至少我的代碼沒有問題 – Marinka 2012-08-07 13:39:55

+0

似乎不適用於'geom_abline',或者我搞砸了嗎?看到我的問題http://stackoverflow.com/questions/43696806/r-ggplot-different-geom-ablines-in-facets – Boern 2017-04-29 14:28:51