>-----Original Message-----
>From: r-help-bounces at stat.math.ethz.ch
>[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Andy Bunn
>Sent: Wednesday, March 19, 2003 12:15 PM
>To: r-help at stat.math.ethz.ch
>Subject: [R] Time Series-like barplot?
>
>
>I have data structured like the following:
>
>> foo.mat <- matrix(NA, ncol = 5, nrow = 10)
>> foo.mat[2:6,1] <- 1
>> foo.mat[1:3,2] <- 1
>> foo.mat[3:10,3] <- 1
>> foo.mat[1:10,4] <- 1
>> foo.mat[8:10,5] <- 1
>> foo.mat
> [,1] [,2] [,3] [,4] [,5]
> [1,] NA 1 NA 1 NA
> [2,] 1 1 NA 1 NA
> [3,] 1 1 1 1 NA
> [4,] 1 NA 1 1 NA
> [5,] 1 NA 1 1 NA
> [6,] 1 NA 1 1 NA
> [7,] NA NA 1 1 NA
> [8,] NA NA 1 1 1
> [9,] NA NA 1 1 1
>[10,] NA NA 1 1 1
>
>I am trying to create a plot with horizontal bars that has
>1:10 on the x-axis and plots the length of the data (i.e., 1)
>in the correct context.
>E.g.,:
>
> 5 ------
> 4 --------------------
> 3 ----------------
> 2 -----
> 1 ---------
> 1-2-3-4-5-6-7-8-9-10
>
>
>Does any body have a suggestion?
>
>Thanks, Andy
How about something like the following with your matrix 'foo.mat' in
place. Somebody else may have (hopefully has) a more efficient
approach or knows of a function.
# Put together a matrix containing the positions
# in foo.mat that have a 1
v1 <- which(foo.mat == 1, arr.ind = TRUE)
# Now get range() for each group (bar)
v2 <- tapply(v1[ , 1], v1[, 2], range)
# Convert to matrix, in this case 5 x 2
v3 <- matrix(unlist(v2), ncol = 2, byrow = TRUE)
# Set up plot window w/ appropriate size
# Add one to y axis to have space below
# and above bars
plot(c(1, max(v3)), c(0, dim(v3)[1] + 1), type = "n", axes = FALSE,
ann = FALSE)
# now draw bars using rect()
rect(v3[, 1], 1:dim(v3)[1] - 0.25, v3[, 2], 1:dim(v3)[1] + 0.25, col
"grey")
# now draw axes
axis(1, at = 1:max(v3))
axis(2, at = 1:dim(v3)[1], las = 2)
# draw box around it
box()
Hope that helps,
Marc Schwartz