[R] Add different types of legend: line and points

Duncan Murdoch murdoch.duncan at gmail.com
Thu Feb 10 23:25:17 CET 2011


On 11-02-10 3:56 PM, Shiguo Jiang wrote:
> Hello,
>
> I plot box plot, and add a point to the box indicating mean. I also add some
> range to the box width. I want to add legend for both the range (line) and
> mean (point). However, I cannot add line legend and point legend together.
> The code looks like the following.

Use NA for the lty in the ones with no lines or for the pch in the ones 
with no points.

Duncan Murdoch
>
> (1) First, I tried the following code, however, it plot a line across the
> point legend("*").
>
> boxplot(count ~ spray, data = InsectSprays)
>
> rb<- boxplot(decrease ~ treatment, data = OrchardSprays, col="lightgrey")
> title("Comparing boxplot()s and non-robust mean +/- SD")
>
> mn.t<- tapply(OrchardSprays$decrease, OrchardSprays$treatment, mean)
> xi<- seq(rb$n)
> points(xi, mn.t, col = "blue", pch = "*")
>
> h1<- abline(h=110, col="red")
> h2<- abline(h=0, col="red", lty="dotted")
>
> legend("topleft", c("110", "0", "mean"),
>          lty = c("solid","dotted"), pch = c(" ", " ", "*"),
>          col = c("red","red", "blue"),lwd = c(1,1))
>
>
>
> (2) I then tried the following
>
> legend("topleft", c("110", "0", "mean"),
>          lty = c("solid","dotted"," "), pch = c(" ", " ", "*"),
>          col = c("red","red", "blue"),lwd = c(1,1))
>
>
> It returns error as lty cannot be " ".
>
> Error in segments(x1, y1, x2, y2, ...) : invalid line type: must be length
> 2, 4, 6 or 8
>
>
> Can anyone help me out? Thank you.
>
> Shiguo
>



More information about the R-help mailing list