我在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)
答案 0 :(得分:2)
感谢评论的一些帮助,我设法产生了预期的结果。这比我想象的容易得多。 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