Capsicum Capsicum - 1 year ago 102
R Question

r add lines or segments to barchart

I have a stacked horizontal bar chart with only one bar. I want to label the different segments, with each label where the respective segment begins. However, because some segments are very narrow, the labels need to be at different levels and should be connected with the bar through a straight line, like in this example.

example bar chart

I can create the barchart using

and the labels using
mtext(..., side=3, line=1,...)
but cannot get the lines.
does not seem to work because coordinates in y-direction do not funtion properly (or I have not yet figured out the coordinate system for bar charts).

Does anybody have a hint on how to create these lines using base graphics?

Answer Source
## bogus data
dat <- c(1,3,1,2)
nb <- length(dat)
## basic barplot
barplot( cbind( dat ), col=1:nb, horiz=TRUE, ylim=c(0,0.7), wid=0.2)

## location of the vertical segments
xdat <- c(0, cumsum(dat[-nb]))

## create vector of jagged heights for label placement/vertical segment ends
h1 <- 0.36
h2 <- 0.4
heights <- c(h2,h1,h2,h1)
segments(x0=xdat, x1=xdat, y0=rep(0.1,nb), y1=heights)
text(x=xdat+0.1, y=heights, paste("Segment",1:nb), adj=0)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download