[R] Overlaying a moving average curve on top of a barplot

Marc Schwartz MSchwartz at medanalytics.com
Mon Feb 3 17:19:03 CET 2003

>-----Original Message-----
>From: r-help-admin at stat.math.ethz.ch 
>[mailto:r-help-admin at stat.math.ethz.ch] On Behalf Of José 
>Santos Alegria
>Sent: Monday, February 03, 2003 5:30 AM
>To: r-help at stat.math.ethz.ch
>Subject: [R] Overlaying a moving average curve on top of a barplot
>I'm using standard barplot (Windows version 1.6.2 of R) to 
>represent a certain weekly metric "v" and I would like to 
>properly overlay on top of it its moving average "mean.8" 
>(window of 8 weeks). I must be doing something wrong since the 
>moving average (using "lines") doesn't overlay properly, i.e., 
>both x-scales do not match!
>barplot(v[8:length(v)], col=7)
>lines(mean.8[1:length(mean.8)],   lty=1, lwd=2, col=2)
>How do I make sure that both graphics are in synch as far as 
>the x-scale and y-scales are concerned?
>José A. S. Alegria

The problem that you are having is that you need to get the bar
midpoints from barplot() in order to use those values as the x
coordinate values for lines().  barplot() returns the bar midpoints as
an invisible vector (or matrix where appropriate).

Modify your code to:

mp <- barplot(v[8:length(v)], col=7)
lines(mp, mean.8[1:length(mean.8)],   lty=1, lwd=2, col=2)

This puts the bar midpoints (x axis values) in mp, which you can then
use for lines().



More information about the R-help mailing list