Plot time series with mean and vertical error bars of interquartile range by column in R

折月煮酒 提交于 2019-12-14 04:14:56

问题


I have a matrix and want to plot vertical error bars of the interquartile range and mean by column from the matrix. How do I do this in R especially ggplot2, please? A sample matrix is given below:

 ##Create matrix
 B = matrix (c(2,4,3,1,5,7,5,3,8,3,7,3),nrow=4,ncol=3) 
 ##Create zoo object
 B2<-as.zoo(B)
 colnames(B2)<- c("A","B","C")

 B2
          A B C
          2 5 8
          4 7 3
          3 5 7
          1 3 3
##The Dates for the columns:
Date<-as.yearmon (seq(as.Date("2000/1/1"), by = "month", length.out = 3))

I want a time series plot but with a row based vertical IQR error bar for each timestamp. Here's a sample of the outcome I am trying to achieve' However, rather than have towns on the x-axis, I will have the row id or date.


回答1:


I had to go the long way round with this so here's what I did (Using the 25% and 75% percentile):

##Create matrix
B = matrix (c(2,4,3,1,5,7,5,3,8,3,7,3),nrow=4,ncol=3) 
##Create dataframe
B2<-as.data.frame(B)
colnames(B2)<- c("A","B","C")
##Create date sequence
##To compute quantile by row
D<-apply(B2,2,quantile)
##Select 1st and 3rd quartile (25% and 75%) and transpose to make them columns.
D2<-t(D[c(2,4),])
##Mean
CO<-apply(B2,2,mean)
DM<-as.data.frame(cbind(D2,CO))
##Create dates
Date<-as.character(as.yearmon (seq(as.Date("2000/1/1"), by = "month", length.out = 3)))
##Add to dataframe 
DM$Date<-Date
colnames(DM)<-c("Q1","Q3","CO","Date")

##Plot using ggplot2 
library(ggplot2) 
ggplot(DM, aes(x=Date, y=CO,group=1,colour="CO")) + 
geom_errorbar(aes(ymin=Q1, ymax=Q3), width=.1) +
    geom_point(size=3) +
geom_line(aes())  

Here's the result with the time series line connecting the mean for each month:

I won't mind an easier way of doing this if there are any ideas.



来源:https://stackoverflow.com/questions/36167800/plot-time-series-with-mean-and-vertical-error-bars-of-interquartile-range-by-col

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!