[R] Help with multicolored points in one plot

Deepayan Sarkar deepayan at stat.wisc.edu
Thu Feb 26 17:55:42 CET 2004


On Thursday 26 February 2004 10:13, David Thibault wrote:
> Hello all,
>
> I have a situation where I'd like to plot points from multiple groups of
> data in one plot.  I'd like each group's points to be colored a
> different color.  I've seen people comment on how you can alternate
> colors by providing a range of colors and then it will loop through each
> color as it plots individual points.  However, that just goes by
> individual points and not by group.
>
> Next I thought if, for example, I had 2 groups, I could make a 2 color
> vector.  Then I could merge the data from my two groups alternating into
> an X and Y vector, but that doesn't work either because the 2 groups may
> not have equal numbers of members.  For example
> -------------------------------
> Group1_Xdata <- c(1,2,3,4,5)
> Group2_Xdata <- c(10,20,30,40,50)
>
> Colors <- c("red","blue")
> Merged_XData <- c(1,10,2,10,3,30,4,40,5,50)
>
> (SAME MERGE FOR Y DATA)
> -----------------------------
> That would work to make group1 red and group2 blue, but if Group 2 had 6
> members instead of 5, then the 6th member would come out red.
>
> Any thoughts?  Also, I want to be able to code this generically enough
> that I can have any number of groups and colors.

Trellis graphics (using the lattice package in R) has a fairly systematic 
approach for doing this. See example(xyplot) for some examples. For your 
data, a possible usage could be:

x <- c(Group1_Xdata, Group2_Xdata)
y <- c(Group1_Ydata, Group2_Ydata)
g <- c(rep(1, length(Group1_Xdata)), rep(2, length(Group2_Xdata)))

xyplot(y ~ x, groups = g)

or if you want to control the colors

xyplot(y ~ x, groups = g, col = c("red", "blue"))


With base graphics, something similar could be achieved with 

plot(x, y, col = c("red", "blue")[g])

lattice is more systematic in the sense that it has globally modifiable 
settings to control various graphical parameters (not only color) used to 
distinguish between groups, with reasonable defaults.

Hth,

Deepayan




More information about the R-help mailing list