[R] Bar Plot with Connected Points on 1 Y-Axis

Marc Schwartz marc_schwartz at comcast.net
Wed Jan 7 04:56:49 CET 2009


on 01/06/2009 09:07 PM jimdare wrote:
> Hi Everyone,
> 
> Have created a bar plot of the data below using the following code: 
> barplot(TACC,space=0,names.arg=Year).  I now want to add a series of
> connected points to represent the catch. I tried to do this using
> line(Catch) or points(Catch), however both of these commands result in each
> data point being aligned with the right edge of each bar.  I need them to be
> solid points in the centre of each bar, and for each point to be connected
> to its neighbour by a line.  Another issue I have is when the points exceed
> the values for the bar graph (e.g. in 2004 and 2005 catch>TACC) R seems to
> cut them off, I need the axis to be expanded so they can be seen.  I'm sure
> these are relatively simple problems but I am really stuck.  Thanks very
> much for all your help, it is much appreciated.
> 
> James 
> 
> DATA:
> 
>   Year  Species Stock TACC Catch
> 1 2001    ORH    OR1   5000  4687
> 2 2002    ORH    OR1   6000  3215
> 3 2003    ORH    OR1   7000  6782
> 4 2004    ORH    OR1   9000 10000
> 5 2005    ORH    OR1   9000 12000

One key point to note is that barplot() returns the bar midpoints. This
is noted in the help for barplot(). The bars are not centered on integer
axis values, so you need the returned values to place additional
annotation in the proper location relative to the bars.

The other thing is to set the range of the y axis using the maximum
value in Catch, plus some fudge, so that the plot covers both sets of
data and has enough room for the additional points.

Thus, presuming that your data is in a data frame called 'DF':

mp <- barplot(DF$TACC, space = 0, names.arg = DF$Year,
              ylim = c(0, 13000))

# Now use lines() to add Catch
lines(mp, DF$Catch, type = "b", pch = 19)

See ?barplot, ?lines and ?points for more information.

HTH,

Marc Schwartz




More information about the R-help mailing list