Search code examples
rggplot2data-visualizationfigure

How can I color fill each data point to the corresponding subject in R?


I have a set of data where subjects were measured at 2 time points (PRE/POST) under 2 treatment conditions (REST/SMR).

I have the data plotted by time/condition, and also show each individual data point.

SUBJ<-as.factor(c(rep('S01', 5), rep('S02', 5)))
COND<-rep(c('BASELINE','REST_PRE', 'REST_POST', 'SMR_PRE', 'SMR_POST'), 2)
VAR<-c(5.240, 5.774, 5.241, 5.260, 5.168, 5.110, 4.996, 5.006, 5.176, 5.038)

example<-data.frame(SUBJ, COND, VAR)

ggplot(subset(example, COND !='BASELINE')) + geom_boxplot(aes(x= COND, y=VAR, 
group = COND, color = COND), linetype = c(1, 2, 1, 2)) + 
scale_color_manual(values = c('black','black', 'gray40', 'gray40')) + 
geom_dotplot(aes(x= COND, y=VAR, group = COND, color = COND), binaxis = 'y', 
stackdir = 'center', binwidth = 0.08, dotsize = 0.5) + labs(x = NULL, y = 'm', 
size = 10) + theme(plot.title=element_text(hjust = 0.5,size = 12)) + theme_bw() 
+ theme(legend.position = 'none')

I would like each data point to be color coded to each subject. I have tried adding color = subject or fill = subject as an aesthetic is several places, along with scale_fill_manual and scale_color_manual and nothing seems to work. Any help would be much appreciated.


Solution

  • As mentioned in my comment - I think the better choice would be geom_point in your case!

    It think you did everything right. But overlooked that setting the color aesthetic for geom_dotplot only changes a tiny stroke which is invisible due to the fill. You have to set both fill and color:

    edit Setting the same aesthetic (color) for two different variables is very, very, very tricky, and rarely necessary. Use fill for geom_dotplot. (or better for geom_point)

    library(ggplot2)
    
    SUBJ<-as.factor(c(rep('S01', 5), rep('S02', 5)))
    COND<-rep(c('BASELINE','REST_PRE', 'REST_POST', 'SMR_PRE', 'SMR_POST'), 2)
    VAR<-c(5.240, 5.774, 5.241, 5.260, 5.168, 5.110, 4.996, 5.006, 5.176, 5.038)
    
    example<-data.frame(SUBJ, COND, VAR)
    
    ggplot(subset(example, COND !='BASELINE')) + 
      geom_boxplot(aes(x= COND, y=VAR, color = COND), linetype = c(1, 2, 1, 2)) + 
      geom_dotplot(aes(x= COND, y=VAR, color = COND, fill = SUBJ), binaxis = 'y', 
                   stackdir = 'center', binwidth = 0.08, dotsize = 0.5) +
    
      scale_color_manual(values = c('black','black', 'gray40', 'gray40')) 
    

    Created on 2019-08-07 by the reprex package (v0.2.1)