Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

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

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. enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...