Search code examples
rplotcolorsstripchart

Define color for each datapoint in a stripchart separately


I would like to define the color of each data point on a stripchart separately to add an extra information layer on the stripchart. I did not find a solution

I am aware of Different coloring of groups in R plot, and the answer suggests it is not possible per data point. Am I right?

A way around it could be to plot it column by column in a for loop, but then the x-positions are messed up

d = c (1,3,4);
e = c (2,3,4)
f = c (2,6,5)
data = list (d, e, f)
stripchart (data, vertical =T, pch =21, bg = 1, col=2)

Lets say, I would like to color primes in red, non-primes in blue. Or even and odd.

The most universal solution would take a color-list of same dimension as input, where each value defines the color of the corresponding data point plotted.


Solution

  • Then it is still simpler to plot them 1 by 1, and use bg= parameter:

    # generate fake data
    datalist = list( rnorm(100), rnorm(100, sd = 1),rnorm(100, sd = 2) )
    # generate color value for each data point  (say I want to color by each values sign +/-)
    colorlist = lapply(datalist, sign)
    plot(0,0,type="n",xlim=c(0.5,3.5), ylim=c(-10,10),  xaxt = 'n', xlab ="", ylab = "value",  main ="Smear")
    for (i in 1:3) { stripchart(na.omit(datalist[[i]]), at = i, add = T, bg = colorlist[[i]]+2, vertical = T, pch =21, method = "jitter") }
    axis(side=1,at=1:3,labels=3:1)