ggplot change variable default color

Hi, I have this ggplot and I want paint one gender in grey color and the other one in white. This is my code:

library(tidyverse)

my_data <- tibble(Var_1 = c(900, 1500, 350, 1200, 750, 100,125,250,300),
                  Var_2 = c(385, 988, 150, 355,555, 900,20, 25, 500),
                  Gender = c("W", "W", "W", "M", "M", "W", "W", "M", "W"),
                  my_weights = c(2.2, 3.1, 8.2, 4.2, 5.3, 6.8, 12, 25, 1))

my_data %>%
  ggplot(aes(Gender, Var_1, weight = my_weights, fill = Gender))+
  geom_violin(color = "black", scale = "count")

And my figure here. The idea is to change the pink color for grey and the blue/green for white.

Rplot

Hi Lucas, you need to change your filling by using one of the scale_*() functions that allow you to change the specific aesthetic. In your case we need the family scale_fill_*() and since your data is categorical we can use the scale_fill_manual() function:

library(tidyverse)

my_data <- tibble(Var_1 = c(900, 1500, 350, 1200, 750, 100,125,250,300),
                  Var_2 = c(385, 988, 150, 355,555, 900,20, 25, 500),
                  Gender = c("W", "W", "W", "M", "M", "W", "W", "M", "W"),
                  my_weights = c(2.2, 3.1, 8.2, 4.2, 5.3, 6.8, 12, 25, 1))

my_data %>%
  ggplot(aes(Gender, Var_1, weight = my_weights, fill = Gender))+
  geom_violin(color = "black", scale = "count") +
  scale_fill_manual(values = c("grey", "white"))

Created on 2020-06-25 by the reprex package (v0.3.0)

Please use tags when asking questions, it was pure luck I have seen it but it might get buried soon since most people (I guess) answer questions related to specific tags.

Cheers, Cédric

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.