I am trying to generate a barplot with R with different widths of the bars and different spaces between them. For example I have a matrix
data <- matrix(c(1,2,2,4,7,1,11,12,3), ncol = 3, byrow = T)
colnames(data) <- c("Start", "Stop", "Height")
And I would like to generate a figure like this (sorry for the sketch):
| __
| __ | |
| | | ________ | |
| | | | | | |
------------------- ------------------
0 1 2 3 4 5 6 7 8 9 10 11 12
As far as I understand, barplot() allows you to specify the width but the space between the bars can only be expressed as a fraction of the average bar width. However, I would like to specify specific (integer) numbers for the spaces between the bars. I'll appreciate any hints/ideas!
A standard bar chart should have gaps between bars that are slightly narrower than the bars. The exceptions to this are the exception of histograms and clustered bar charts.
Until research is done to determine the ratio between bar length and width below which problems begin to occur, a minimum 10:1 ratio is probably a good rule of thumb to follow, with spaces between bars in the range of 50% to 75% of their widths.
Set the width of geom_bar() to a small value to obtain narrower bars with more space between them. By default, the width of bars is 0.9 (90% of the resolution of the data). You can set this argument to a lower value to get bars that are narrower with more space between them.
One way of getting what you want is to create dummy, empty bars. For example,
##h specifies the heights
##Dummy bars have zero heights
h = c(0, 2, 0, 1, 0, 3)
w = c(1, 1, 2, 3, 4, 1)
Then plot using a barplot
##For the dummy bars, remove the border
##Also set the space=0 to get the correct axis
barplot(h, width=w, border=c(NA, "black"), space=0)
axis(1, 0:14)
If you divide the space
argument by mean(Width)
you can also get there:
data <- as.data.frame(data)
data$Width <- with(data, Stop - Start)
data$Space <- with(data, Start - c(0,head(Stop,-1)))
with(data, barplot(Height, Width, space=Space/mean(Width), xlim=c(0,13) ) )
axis(1,0:14)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With