2017-04-01 27 views
0

我是R和ggplot2的新手。任何幫助深表感謝!我這裏有一個數據集,我試圖繪製帶標準偏差和範圍的框圖

weight band mean_1  mean_2 SD_1  SD_2 min_1 min_2 max_1 max_2 
    1   5   .   3  . 0.17  . 27 . 
    2   6   .   3.7  .  1.1  . 23 . 
    3   8   8   4.3  4.1  1 1.749 27 27 
    4   8   9   3.3  6  2.3 1.402 13 42 

在這組數據中,我試圖繪製平均1的條形圖和給定的weight_band下意味着2並排(1-4 )並將最小誤差(分別爲1 & 2)和最大誤差(分別爲1)。 「。」指出沒有數據。

我瀏覽過stackoverflow和其他網站,但沒有找到我正在尋找的解決方案。

我的代碼如下:

sk1 <- read.csv(file="analysis.csv")  

library(reshape2) 

sk2 <- melt(sk1,id.vars = "Weight_band") 
c <- ggplot(sk2, aes(x = Weight_band, y = value, fill = variable)) 
c + geom_bar(stat = "identity", position="dodge") 

但是,使用這種方法,它不圖限制爲僅僅繪製的平均值。是否有一組代碼可以這樣做?此外,是否有方法將最小值和最大值作爲誤差線應用於各自的均值?我提前感謝大家。這將幫助我大大推進我的r GGPLOT2功能的認識

回答

1

這應該讓你關閉,我們需要做一些更多的數據清洗和重新塑造,使ggplot快樂:)

library(reshape2) 

df <- read.table(text = "weight_band mean_1  mean_2 SD_1  SD_2 min_1 min_2 max_1 max_2 
       1   5   .   3  . 0.17  . 27 . 
       2   6   .   3.7  .  1.1  . 23 . 
       3   8   8   4.3  4.1  1 1.749 27 27 
       4   8   9   3.3  6  2.3 1.402 13 42", header = T) 
sk2 <- melt(df,id.vars = "weight_band") 

## Clean 

sk2$group <- gsub(".*_(\\d)", "\\1", sk2$variable) 
# new column used for color or fill aes and position dodging 
sk2$variable <- gsub("_.*", "", sk2$variable) 
# make these variables universal not group specific 

## Reshape again 

sk3 <- dcast(sk2, weight_band + group ~ variable) 
# spread it back to kinda wide format 
sk3 <- dplyr::mutate_if(sk3, is.character, as.numeric) 
# convert every column to numeric if character now 

# plot values seem a little wonky but the plot is coming together 
ggplot(sk3, aes(x = as.factor(weight_band), y = mean, color = as.factor(group))) + 
    geom_bar(position = "dodge", stat = "identity") + 
    geom_errorbar(aes(ymax = max, ymin = min), position = "dodge") 

enter image description here

+1

哇!非常感謝。這絕對有助於很多! –

+0

只是一個簡單的問題。我嘗試用'code'scale_colour_manual(「group」,breaks = c(1,2),values = c(「#0072B2」,「#009E73」))''code「更改重量帶的覆蓋,但它沒有沒有工作。我很可能錯誤地編碼它。 –

+0

嘗試使用'+ scale_colour_manual(values = c(「#0072B2」,「#009E73」))'代替 – Nate