我在为我的两个不同的facet_grids获取不同的颜色方面遇到了困难。
这是一个简单的示例:
df <- data.frame(x = rep(1:20, each=20), y= rep(1:20, 20),
val = sample(0:1,400, replace=TRUE),
facet_grid = c(rep("A", 200), rep("B", 200)))
colors <- c(1,2)
ggplot(df, aes(x = x, y = y)) +
geom_tile(aes(fill = val)) +
facet_grid(. ~ facet_grid, scales = "free") +
scale_fill_gradient(limits=c(0,1), low=brewer.pal(11, "RdYlGn")[colors][1],
high="grey30")
我正在使用
scale_fill_gradient
函数和brewer.pal
函数来覆盖标准颜色。然而,我想要实现的是在两个不同的facet_grids中,对于值为1应该使用相同的颜色(灰色30)。对于在第一个facet_grig中为0的值,例如,应该使用红色,在第二个facet_grid中应该使用绿色。请问有人可以给我一些提示如何实现吗?我创建了另一个示例,现在更接近我想要的,但我不理解为什么
scale_fill_identity
无法工作。因此,我稍微更改了数据框,使值现在具有4个不同的值:df <- data.frame(x = rep(1:20, each=20), y= rep(1:20, 20),
val = c(sample(0:1,200, replace=TRUE), sample(2:3,200, replace=TRUE)),
facet_grid = c(rep("A", 200), rep("B", 200)))
ggplot(df, aes(x = x, y = y)) +
geom_tile(aes(fill = val)) +
facet_grid(. ~ facet_grid, scales = "free")
ggplot(df, aes(x = x, y = y)) +
geom_tile(aes(fill = val)) +
facet_grid(. ~ facet_grid, scales = "free")
scale_fill_identity(labels=letters[1:4], breaks=c("red","blue","green","brown")) +
第一个 ggplot 几乎给了我想要的东西。在两个不同的 facet_grids 中有 4 种不同的颜色。我尝试使用 scale_fill_identity
来改变这 4 种颜色,但是在我的图中得到的是 4 种不同的颜色,即黑白和红绿,而不是上面指定的颜色。