2017-04-10 161 views
0

我有兩張數據表,一張帶有我想繪製的點(第一個數據集中的每個點是不同測量的平均值),第二個數據包含標準每個點的偏差。使用Errobar的多線圖來自兩個表格的數據

下面我附上了一個R腳本來創建從第一個數據,它工作正常lineplot。隨着代碼我可以創建類似下面的

enter image description here

現在我想用第二個表(標準差)來創建一個情節類似以前的,但現在也呈現出errorbar,即一個情節,那以圖形方式顯示每個測量的標準偏差,如this

library(ggplot2) 

##loads a dataframe and returns a ggplot object that can be externally modified and plotted 
makeMultipleLinePlot <- function(data){ 

    require(reshape2) 
    data$id <-rownames(data) 
    melted <- melt(data) 
    colnames(melted)<-c("Measurement","Month","Percentage") 
    g<-ggplot(data=melted, 
      aes(x=Month, y=Percentage, color=Measurement,group=Measurement)) + 
    geom_line(size=1,alpha=0.8) + geom_point(size=4,aes(shape=Measurement)) 
    return(g) 
} 


##load a table from google sheets. assumes the sheet has a single table 
loadTableFromGoogleSheet <- function(url, sheet) { 
    require(gsheet) 
    a <- gsheet2text(url,sheetid=sheet, format='csv') 
    data <- read.csv(text=a, stringsAsFactors=FALSE,header = TRUE,row.names = 1) 
    return(data) 
} 


#URL of the google spreadsheet 
url <- "docs.google.com/spreadsheets/d/10clnt9isJp_8Sr7A8ejhKEZXCQ279wGP4sdygsit1LQ" 

gid.humidity <- 2080295295 #gid of the google sheet containing humidity data 
data.humidity<-loadTableFromGoogleSheet(url,gid.humidity) 

gid.humidity_sd <- 1568896731 #gid of the google sheet containing standard deviations for each measurement in the humidity data 
data.humidity_sd<-loadTableFromGoogleSheet(url,gid.humidity_sd) 

ggsave(filename="lineplot/humidity.pdf", plot=makeMultipleLinePlot(data.humidity)) 
#ggsave(filename="lineplot/humidity.pdf", plot=makeMultipleErrorPlot(data.humidity,data.humidity_sd)) 
+0

看到http://docs.ggplot2.org/0.9.3.1/geom_errorbar .html你可以使用'geom_errorbar(data = data2,aes(x,sd))將錯誤條添加到你的點上。' –

回答

0

這整潔兩data.frame,加入他們的行列plot結果,使用geom_errorbar

library(dplyr) 
library(tidyr) 
library(ggplot2) 

df <- data.humidity %>% 
    mutate(measure = row.names(.)) %>% 
    gather(month, value, -measure) 


df_sd <- data.humidity_sd %>% 
    mutate(measure = substr(row.names(.), 1, 2)) %>% 
    gather(month, sd, -measure) 

dfF <- full_join(df, df_sd) 
#> Joining, by = c("measure", "month") 


ggplot(dfF, aes(month, value, group = measure, color = measure))+ 
    geom_line(size=1,alpha=0.8) + 
    geom_point(aes(shape = measure)) + 
    geom_errorbar(aes(ymin = value - sd, ymax = value + sd), width = .3) 

+0

這樣可以非常優雅地解決問題,非常感謝! – user11924

相關問題