Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify spaces between bars in barplot

Tags:

plot

r

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!

like image 542
roschu Avatar asked May 10 '13 12:05

roschu


People also ask

Should you leave gaps between bars in a bar graph?

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.

What is the ideal space between bars in a bar chart?

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.

How do I add a space between bars in ggplot2?

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.


2 Answers

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)

enter image description here

like image 171
csgillespie Avatar answered Oct 15 '22 14:10

csgillespie


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)

enter image description here

like image 27
thelatemail Avatar answered Oct 15 '22 13:10

thelatemail