Color points according to column

I am trying to make a stripchart() with dots colored using a simple palette. This is a small example with my attempt:

df = data.frame(V1=runif(100,-1,1), V2=runif(100,0,1))

stripchart(df$V2, method="jitter", 
           col=factor(df$V1), 
           vertical=TRUE, pch=19, add=FALSE,
           cex=0.8, jitter=0.2, at=1)

However, I haven't been able to color de dots as I want, that is, plot the values of the 2nd column with colors according to the values of the 1st column.

If possible, I would like to use a red-blue palette like RColorBrewer::brewer.pal(n=10, name="RdYlBu"), but I am not sure how to implement it.

Does anyone know how to do this in R?

Any help would be appreciated, thanks in advance!

Would you consider using ggplot2 ?
ggplot2 stripchart (jitter) : Quick start guide - R software and data visualization - Easy Guides - Wiki - STHDA

Honestly, I would prefer using base R. But I am not sure if it is possible

You need to change two things in your example:

  1. The factor should be associated to discrete values, if you have 100 random numbers generally you have 100 different factors (and thus 100 different colors), then to index the colour you need to use something else (or use cut for example)
  2. You need to change pch to 21 and use bg rather than color. I don't know why but in this way it works.

The second point seems an inconsistency between plot and stripchart. If you do plot(1:10, col = 1:10) you get 10 different colours but with stripcharts I wasn't able to use col in this way but only bg.

set.seed(42)
df = data.frame(V1=sample.int(10,100,replace=TRUE), V2=runif(100,0,1))

df$col <- RColorBrewer::brewer.pal(n=10, name="RdYlBu")[df$V1]
head(df)
library(dplyr)

group_by(df,V1) %>% group_walk(~{stripchart(pull(.,V2), method="jitter", 
                                          col=I(pull(.,col)),
                                          vertical=TRUE, pch=19,
                                          add=min(pull(.,V1))!=1,
                                          cex=0.8, jitter=0.2, at=1)},
                               .keep=TRUE)

image

Thanks for your answer! It is a good solution

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.