带有Errobar的多个线图,用于来自两个表的数据

时间:2017-04-10 15:49:01

标签: r ggplot2 errorbar

我有两个数据表,一个是我要绘制的点(第一个数据集中的每个点是不同测量值的平均值),第二个数据包含每个点的标准偏差。

下面我附加了一个R脚本,用于从第一个数据中创建行图,该脚本工作正常。使用代码我可以创建如下的情节

enter image description here

现在我想使用第二个表(标准偏差)创建一个类似于前一个的图,但现在也显示一个错误栏,即以图形方式显示每个测量的标准偏差,如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))  

1 个答案:

答案 0 :(得分: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)