【问题标题】:Prescribe same color map based on specific factors根据特定因素规定相同的颜色图
【发布时间】:2017-11-30 00:48:07
【问题描述】:

我在 ggplot2 中进行颜色映射时遇到了一些困难。四个地块中有两个具有相同的六个县变量。但是,“一氧化碳”和“粗颗粒物”子图只有五个(缺少皮尔斯县)。

每种污染物在 y 轴上都有不同的单位,在单个 ggplot 中标记各个方面是一项挑战。为了解决这个问题,我分别生成每个图,然后使用gridExtra 将它们组合在一起。

是否可以将来自六个县的三个地块的相同颜色映射应用于一氧化碳地块?

这是我如何制作单个情节的示例:

library(ggplot2)
library(dplyr)
library(gridExtra)


p1 <- ggplot(filter(df, pollutant == "Nitrogen dioxide"), aes(x = as.factor(season), y = value, fill = as.factor(county))) + 
    geom_boxplot(position = "dodge")

    ## I'm excluding a bunch of code to format the font and size of the title/legend/axis labels


g <- grid.extra(p1, p2, p3, p4)

【问题讨论】:

  • 使用scale_color_manual 为每个县分配相同的颜色,无论特定地块中是否存在特定县。 Here's an example.
  • 在对 6 个因子水平使用 scale_color_manual 时,有没有办法分配 ggplot2 的默认调色板?
  • library(scales) 然后hue_pal()(6) 应该给出默认ggplot2 调色板的前6种颜色。
  • 非常感谢!我一直想知道如何做到这一点......

标签: r plot ggplot2 gridextra


【解决方案1】:

感谢 cmets 的一些帮助,我已经设法产生了预期的结果。这比我想象的要容易得多。 hue_pal() 函数将来肯定会对我有用。谢谢大家!

library(scales)

## determine what the default color palette is for ggplot2 with 6 factor levels:
hue_pal()(6)
#[1] "#F8766D" "#B79F00" "#00BA38" "#00BFC4" "#619CFF" "#F564E3"

## next we need to create a custom color palette using these six colors:
cols <- c("Ada" = "#F8766D", "Bernalillo" = "#B79F00",
          "Multnomah" = "#00BA38", "Pierce" = "#00BFC4",
          "Sacramento" = "#619CFF", "Salt Lake" = "#F564E3")

## I'm mapping each color to the specific factor level (County Name)
## This ensures that each county maintains the same color throughout each plot
## regardless if there are 5 or 6 factor levels!

p1 <- ggplot(filter(df, pollutant == "Nitrogen dioxide"),
             aes(x = as.factor(season),
                 y = value,
                 fill = as.factor(county))) + 
      geom_boxplot(position = "dodge") + 

      ## here's where we'll add our custom color palette:
      scale_fill_manual(values = cols)

p1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-08-13
    • 2023-03-28
    相关资源
    最近更新 更多