[R] Barplot with lines

Jim Lemon jim at bitwrit.com.au
Fri Nov 23 09:13:42 CET 2012


On 11/23/2012 06:33 PM, Ripples wrote:
> Hi,
>
> I'm trying to plot stacked barplot with lines on it.  Here is the data.
>
> emp days val1 val2 score
> 1 21 1 0 1200
> 2 35 1 1 na
> 3 42 na na 3000
> 4 53 2 1 2100
> 5 64 1 0 na
> 6 73 na na 1400
>
> My X-axis is days. I'm looking to plot val1,val2 as stacked bars and score
> as lines with different y-axis. I could get the bar plot and lines on it
> but the problem is the bars and lines are not aligning well for same point
> on X-axis. Note, that there might not be a score for some when there is
> val1 and val2 or vice versa. Any help in this regard is highly appreciated.
>
Hi SK,
Your alignment problem is due to the way barplot spaces the bars. Try this:

mydata<-read.table(textConnection(
  "emp days val1 val2 score
  1 21 1 0 1200
  2 35 1 1 na
  3 42 na na 3000
  4 53 2 1 2100
  5 64 1 0 na
  6 73 na na 1400"),
  header=TRUE,na.strings="na")
barpos<-barplot(as.matrix(mydata[c(1,2,4,5),c("val1","val2")]))

Then use "barpos" as the x locations of your values for the lines.

Jim




More information about the R-help mailing list