[R] pch with plot and legend

Paul Murrell p.murrell at auckland.ac.nz
Wed Jul 25 23:56:48 CEST 2001


Hi


> I'm trying to plot a scatterplot of two variables using pch to plot
> different characters based on a third factor. Here is my example
>
> > data("ToothGrowth")
> > attach(ToothGrowth)
> > levels(supp)
> [1] "OJ" "VC"
> > plot(len ~ dose,pch=as.numeric(supp))
> > legend(locator(1),pch=as.numeric(supp),legend=levels(supp))
>
> The command as.numeric(supp) returns 2 2 2 2 ...  1 1 1 ... for the
> factor supp which the plot command uses nicely, but the pch command
> for the legend uses the first two values 2 2 for the command. This
> isn't correct of course. How can I get the correct numbers for the pch
> command for the levels? I tried pch=as.numeric(levels(supp)) in legend
> but that didn't work.


The simple answer is ...

    legend(locator(1),pch=1:2,legend=levels(supp))

... because the numeric equivalent of the levels of a factor are the
integers 1:nlevels(<factor>)

This might be viewed as a not very nice programming style because
it makes use of knowledge of the underlying implementation of factors.
A more complicated and harder to understand, but possibly more pure
solution might be ...

    legend(locator(1),pch=as.numeric(supp[match(levels(supp),
supp)]),legend=levels(supp))

Paul


-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list