如何更改 ggplot2 的默认颜色?

时间:2021-06-18 13:54:12

标签: r ggplot2

我想知道如何把第二张图片的颜色改成第一张 我是 ggplot2 的新手,仍在学习 atm

library(tidyverse)
data(mpg)
ggplot(data = diamonds) +
          geom_bar(
            mapping = aes(x = cut, fill = clarity),
            position = "dodge"
          )

我以为我会在第一张图片中得到很多颜色,但在第二张图片中我得到了颜色。First pic Second pic

1 个答案:

答案 0 :(得分:0)

您可以使用多种方法更改颜色。下面是几个例子:

  1. 您可以使用 this 等页面中的代码并使用 scale_fill_manual
  2. 指定手动颜色
    ggplot(diamonds, aes(cut))+
      geom_bar(position = "dodge", aes(fill = clarity))+
      scale_fill_manual(values = c("#0CFCA0", "#A54408", "#E53975", "#7FB0FF", 
                                   "#4ACC0A", "#51397F", "#FFC059", "#062C7F"))

创建这个:Manual colours - excuse the choices, they were at random

This page 的代码来自您在第一张图片中显示的 ggplot2 默认颜色。

  1. 正如 maarvd 上面提到的,您可以使用 RColorBrewer
    ggplot(diamonds, aes(cut))+
      geom_bar(position = "dodge", aes(fill = clarity))+
      scale_fill_brewer(palette = "RdYlBu")

创建这个:Brewer colours