Reputation: 4084
Basically, I am trying to use R to create a graphic in which I can make rectangles of various lengths at certain locations on a plot's X-axis. So, with some R code using something like ggplot2, I would make a graphic that looks something like this:
---- ----------------- -----------------
....| |--------| |------------------------------| |
---- ----------------- -----------------
Sorry for the stupid ASCII art!
The only ggplot2 function I could find is geom_errorbarh
, but this of coruse just gives horizontal error bars and not boxes. Also, I want the boxes to be filled with color and have labels, if possible. And, I'm not confined to ggplot2, I can use anything within R, I just thought ggplot2 might be the easiest way.
Thanks for any advice!
Upvotes: 4
Views: 3117
Reputation: 38619
This is really easy to do with ggplot. You just need a dataframe setting the starting and ending points for each rectangle, like so:
# Sample data
plot.data <- data.frame(start.points=c(5, 32),
end.points=c(15, 51),
text.label=c("Sample A", "Sample B"))
plot.data$text.position <- (plot.data$start.points + plot.data$end.points)/2
# Plot using ggplot
library(ggplot2)
p <- ggplot(plot.data)
p + geom_rect(aes(xmin=start.points, xmax=end.points, ymin=0, ymax=3),
fill="yellow") +
theme_bw() + geom_text(aes(x=text.position, y=1.5, label=text.label)) +
labs(x=NULL, y=NULL)
Upvotes: 5