使用特定调色板为 ggplot 上色

color ggplot using specific pallette

我如何给图上色使得 -

A1 - 深蓝色, A2——淡蓝色, B1——暗红色, B2 - 淡红色

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()

我随意选了颜色(深蓝~浅红)
您可以在 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`.

reprex package (v2.0.1)

于 2022-05-18 创建

与上面的答案类似,但使用命名的颜色向量更加冗长。

    # 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()