How can I add a polygon to a barplot? The example below puts a line to inadequate position:
a <- matrix(,2,4)
a[1,] <- c(2,4,6,8)
a[2,] <- c(1,3,5,7)
colnames(a) <- c("2014-Q1","2014-Q2","2014-Q3","2014-Q4")
rownames(a)<- c("VzhSlo","ZahSlo")
barplot(a, main="mrasti", xlab="q", col=c("darkblue","red"), legend = rownames(a), beside=TRUE)
b <- c(1.5, 2, 3.5, 4.5)
lines(b,lwd=4,col=3)
SO this plot is not what we expect to produce. The function `lines(b)˙ adds a polygon of vector values above at the indices of the values. We have to find the adequate x-coordiantes.
Several graphical functions ( for example hist and alsobarplot ) return useful info that can help adding lines or points to graphs. SUch infomration is returned in invisible way, so we have to save the results to an object:
bp <- barplot(a, main="mrasti", xlab="q", col=c("darkblue","red"), legend = rownames(a), beside=TRUE)
We can inspect the object
str(bp)
## num [1:2, 1:4] 1.5 2.5 4.5 5.5 7.5 8.5 10.5 11.5
bp
## [,1] [,2] [,3] [,4]
## [1,] 1.5 4.5 7.5 10.5
## [2,] 2.5 5.5 8.5 11.5
and find the explanation of returned matrix in the help page of barplot function
help(barplot)
Value
A numeric vector (or matrix, when beside = TRUE), say mp, giving the coordinates of all the bar midpoints drawn, useful for adding to the graph.
SO our matrix bp holds the midpoints of the blue and red bars in the first and second row, respectively. The polygon should be plotted using the mids of the bar pairs which are column means of midpoints in bp:
colMeans(bp)
## [1] 2 5 8 11
FInnaly we get the barplot with the polygon
bp <- barplot(a, main="mrasti", xlab="q", col=c("darkblue","red"), legend = rownames(a), beside=TRUE)
# dodanih je nekaj okraskov, da se krivulja bolje vidi
lines(colMeans(bp),b,lwd=4,col=3)