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!

Upvotes: 1

Views: 3485

Answers (2)

DPH
DPH

Reputation: 4354

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

Upvotes: 2

tamtam
tamtam

Reputation: 3671

You can add your fill-condition inside the fill argument. And add the transparent color with scale_fill_discrete.

Code

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,
           fill = ifelse(category_b == "down", category_a, NA)
       )
) + 
  geom_point(size = 5,
             shape = 21,
             stroke = 2) +
  scale_fill_discrete(na.value = "transparent") +
  guides(fill = FALSE)

Plot
enter image description here

Upvotes: 3

Related Questions