[R] Horizontal grid in background of barplot

Peter Ehlers ehlers at ucalgary.ca
Mon Sep 3 23:39:50 CEST 2012


On 2012-09-03 12:12, David Arnold wrote:
> All,
>
> I have:
>
> x <- matrix(c(22,3,6,69,9,4,7,81,23,4,22,50),nrow=3,byrow=TRUE)
> rownames(x) <- c("Cold or flu","Headache","Backache");
> colnames(x) <- c("Went to doctor","No response","Did
> nothing","Self-medicated")
> x <- t(x)
> print(x)
> barplot(x,beside=TRUE,
>          ylim=c(0,90),
>          xlab="Ailment",
>          ylab="Percent",
>          legend.text=TRUE,
>          args.legend=list("topright",title="Treatment"))
> abline(h=c(seq(10,90,10)))
> box()
>
>   I'd like to get the horizontal lines in the background.
>
> Any suggestions?

Just plot the bars twice and add the background colour of
the legend region.

  barplot(x,beside=TRUE,
          ylim=c(0,90))

  abline(h=c(seq(10,90,10)))
  box()
  barplot(x,beside=TRUE,
          xlab="Ailment",
          ylab="Percent",
          legend.text=TRUE,
          args.legend=list("topright",title="Treatment",bg="white"),
          add=TRUE)

Peter Ehlers




More information about the R-help mailing list