1

How can I make just the dot plot points be colored using the data$color vector? There should be one red point on the plot

t =c(c(10,4,5,6,7,8,15,2),c(2,5,5,14,16,8,15,17))
g =c(  rep("A",8),rep("B",8))

data = data.frame(group = g ,t = t)
data$label = ""
data$label[10]= "g"
data$color =""
data$color[10]= "red"

library(ggplot2)
library(ggrepel)

myfun<- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}


 ggplot(data, aes(x=g, y=t,label = label 
)) + theme_bw()+
  stat_summary(fun.data = myfun, geom="boxplot")  +
   geom_dotplot(binaxis='y', stackdir='center', dotsize=.5, color = color)

I get an error saying: object 'color' not found

3
  • Look at data - it does not contain a column called color. Try to fix this line data$color[10]= "red". What do you try to achieve with that? Commented Jan 4, 2019 at 18:55
  • updated the data frame Commented Jan 4, 2019 at 18:57
  • Now use aes(color = color). But the output might not exactly be what you are looking for, I suppose. Commented Jan 4, 2019 at 18:57

1 Answer 1

2

ggplot doesn't seem to be looking in data to find the color variable, so you need to tell it where color is located. This worked for me:

t =c(c(10,4,5,6,7,8,15,2),c(2,5,5,14,16,8,15,17))
g =c(  rep("A",8),rep("B",8))

data = data.frame(group = g ,t = t)
data$label = ""
data$label[10]= "g"
data$color <- 'black' # added this to color the other points
data$color[10]= "red"

library(ggplot2)
library(ggrepel)

myfun<- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

ggplot(data, aes(x=g, y=t,label = label)) + theme_bw()+
stat_summary(fun.data = myfun, geom="boxplot")  +
geom_dotplot(aes(fill = color), binaxis='y', stackdir='center', dotsize=.5) + 
scale_fill_identity()

I think a better property to change is fill, but you change it back to color

Edited the ggplot call to incorporate a suggestion about how to make the code more elegant.

Sign up to request clarification or add additional context in comments.

2 Comments

I agree about the use of fill but the way this should be done IMHO is by means of aes(fill = color) ... + scale_fill_identity().
Thanks, that seems like a much more robust approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.