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.
One characteristic of the function superb()
in the package of the same name is that you can provide custom-made functions, either for the central tendency, or more specifically for this question, for the error bar width.
In the present case, you can "attach" a function of width to the mean using the following:
IQR.mean <- function(x) { IQR(x) }
That's it! You then proceed to generate the plot:
library(superb)
library(ggplot2)
#Create matrix
B <- matrix (c(2,4,3,1,5,7,5,3,8,3,7,3),nrow=4,ncol=3)
B2 <- as.data.frame(B)
colnames(B2) <- c("A","B","C")
# Create the date information
Date <- as.yearmon (seq(as.Date("2000/1/1"), by = "month", length.out = 3))
# do the plot
superb(cbind(A, B, C) ~., B2, WSFactors = "Date(3)",
plotStyle = "line",
statistic = "mean", #this is the default
errorbar = "IQR"
) + scale_x_discrete(labels= as.character(Date) ) +
ylab( "CO" )
from which you get
Enjoy!
Note that I am the creator of superb
.