2
votes

I am trying to show a dot plot and color the dots using the d$color. In the current solution setting col = c("red","green") is not dynamic. You can see the first point in the d$color should be green but it appears red. There should be 6 green dots and 4 red dots but there are 6 red and 4 green dots.

The data in the d vector will change all the time so hardcoding col = c("red","green") won't allow for the accurate dot colors. Is there a way to just use col = d$color?

  library(mosaic)
n=10
r =c(seq(1,15,1))
binwidth = 1
dat = sample(r ,n= 1,size = n, replace = TRUE)
d = data.frame( x = dat, color = c(rep("red",n/2), rep("green",n/2)))
d$color[1] = "green"
d
dotPlot(~x,data=d, groups = color, breaks = seq(min(d$x)-binwidth,max(d$x)+binwidth,binwidth), cex = 1, col = c("red","green"))
1

1 Answers

4
votes

Since this is a lattice plot, you need to use "groups" as an argument when you want the separate items in the same panel, and 'col' needs to be a vector of the same length as the number of groups:

dotPlot(~x, groups=color,data=d, breaks = seq(min(d$x)-.1,max(d$x)+.1,.1), col=c("green","red"))

There will be an implicit "factor()"-ing of the d$color column and the order of the colors given to the col-argument needs to match the lexical ordering of the color column that will result so 'green' is first and 'red' is second. If you wanted to do that programmatically it would be col=sort(unique(d$color)).

enter image description here