Search code examples
rggplot2conditional-statementsgeom-point

ggplot, conditional fill geom_point


I am looking for a way to fill geom_point if it meets a condition

Example:

mydata <- tibble(x_var = 1:5, 
                 y_var = runif(5), 
                 category_a = c('yes', 'yes', 'no', 'no', 'yes'),
                 category_b = c('down', 'up', 'up', 'down', 'down')
                 )

ggplot(mydata,
       aes(x = x_var,
           y = y_var,
           color = category_a,
           )
       ) + 
  geom_point(shape = 21,
             size = 5,
             stroke = 2
             )

Plot

I want to fill in the points that meet the condition category_b == 'down' with the same color as category_a and leave the rest without filling, how can I do that? Regards!


Solution

  • an alternative approach can be the usage of to specific shapes and assign them manually. A nice side effect is a more descriptive legend:

    mydata <- tibble(x_var = 1:5, 
                     y_var = runif(5), 
                     category_a = c('yes', 'yes', 'no', 'no', 'yes'),
                     category_b = c('down', 'up', 'up', 'down', 'down'))
    
    # choose circle and dot shapes
    shps <- c(1, 16)
    
    
    ggplot(mydata, aes(x = x_var, y =  y_var, color = category_a, shape= category_b)) +
        geom_point(size = 5, stroke = 2) + 
        # add manually choosen shapes and colors
        scale_shape_manual(values=shapes)
    

    enter image description here