SiH
SiH

Reputation: 1546

color ggplot using specific pallette

How can I color the plots such that -

A1 - Dark blue, A2 - Light blue, B1 - Dark red, B2 - Light red

tbl <- tibble(x = c(rnorm(n = 100, mean = 0, sd = 1),
                    rnorm(n = 100, mean = 0, sd = 0.5),
                    rnorm(n = 100, mean = 4, sd = 1),
                    rnorm(n = 100, mean = 4, sd = 0.5)),
              y = c(rep("A1", 100),
                    rep("A2", 100),
                    rep("B1", 100), 
                    rep("B2", 100))
              )

              
ggplot(data = tbl, 
       aes(x = x,
           fill = y)) + 
  geom_histogram(color = "black",
                 alpha = 0.5) + 
  theme_bw()

Upvotes: 0

Views: 44

Answers (2)

Olabiyi Obayomi
Olabiyi Obayomi

Reputation: 146

Similar to the answer above but a little more verbose using a named vector of colors.

    # Create a named vector of colors
    # There is no R color named "light red" therefore I used red instead. 
    colours <- c(A1= "darkblue", A2="lightblue", B1= "darkred", B2= "red")

    ggplot(data = tbl, 
           aes(x = x,
               fill = y)) + 
      geom_histogram(color = "black",
                     alpha = 0.5) + 
      scale_fill_manual(values = colours) +
      theme_bw()

Upvotes: 1

YH Jang
YH Jang

Reputation: 1338

I arbitrarily chose the colors (Dark blue ~ Light Red).
You can change the colors manually using hexcode in sclae_fill_manual.

tbl <- tibble(x = c(rnorm(n = 100, mean = 0, sd = 1),
                    rnorm(n = 100, mean = 0, sd = 0.5),
                    rnorm(n = 100, mean = 4, sd = 1),
                    rnorm(n = 100, mean = 4, sd = 0.5)),
              y = c(rep("A1", 100),
                    rep("A2", 100),
                    rep("B1", 100), 
                    rep("B2", 100))
)


ggplot(data = tbl, 
       aes(x = x,
           fill = y)) + 
  geom_histogram(color = "black",
                 alpha = 0.5) + 
  scale_fill_manual(values = c('#2C3FF6','#72B5FC','#F62C2C','#F0C3C3'))+
  theme_bw()
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2022-05-18 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions