2013-07-11 141 views
3

我對R相當陌生,所以請對您看到的任何內容發表評論。R:連續x軸上的條形圖(時間縮放)

我有兩個條件下(一個時間點)在不同時間點拍攝的數據,我想將它繪製成一個條形圖,帶有誤差條和條在適當的時間點。

我現在有這個(從另一個問題竊取本網站):

library(ggplot2) 
example <- data.frame(tp = factor(c(0, "14a", "14b", 24, 48, 72)), means = c(1, 2.1, 1.9, 1.8, 1.7, 1.2), std = c(0.3, 0.4, 0.2, 0.6, 0.2, 0.3)) 
ggplot(example, aes(x = tp, y = means)) + 
    geom_bar(position = position_dodge()) + 
    geom_errorbar(aes(ymin=means-std, ymax=means+std)) 

現在我的時間點是一個因素,但事實證明,有一種跨越時間測量的分配不均使得情節不太好看。!

這是我的想象圖:

enter image description here

我找到GGPLOT2包可以給你非常漂亮的圖形,但我有很多困難,瞭解比我有其它的R東西。

+0

我錯過了什麼,也許,你的時間點是一個因素,但在所希望的描繪,他們被視爲數值? 14a和14b在哪裏? – agstudy

回答

2

在我們進入R之前,你必須認識到,即使在條形圖中,x軸也需要一個數值。如果您將它們視爲因素,那麼默認情況下軟件會假定條形之間的間距相等。在這種情況下,每個條的x值是多少?它可以是(0,14,14,24,48,72),但是它會在第14點畫出兩條你並不想看到的條。所以你必須拿出x值。

Joran通過在位置14通過修改joran使棒落入在x軸的正確位置中給出的代碼修改所述條的寬度提供了一個很好的解決方案中,最終的解決方案是:

library(ggplot2) 
example <- data.frame(tp = factor(c(0, "14a", "14b", 24, 48, 72)), means = c(1, 2.1, 1.9, 1.8, 1.7, 1.2), std = c(0.3, 0.4, 0.2, 0.6, 0.2, 0.3)) 

example$tp1 <- gsub("a|b","",example$tp) 
example$grp <- c('a','a','b','a','a','a') 
example$tp2 <- as.numeric(example$tp1) 

ggplot(example, aes(x = tp2, y = means,fill = grp)) + 
    geom_bar(position = "dodge",stat = "identity") + 
    geom_errorbar(aes(ymin=means-std, ymax=means+std),position = "dodge") 

enter image description here

+0

謝謝,我應該發現那個細節。我會刪除您的其他答案,並將其作爲本文討論的一部分。它並不是很好。 – joran

+0

謝謝,我編輯了答案並刪除了我的其他答案。 –