不同的颜色对应不同的分面网格

6

我在为我的两个不同的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 种不同的颜色,即黑白和红绿,而不是上面指定的颜色。

1个回答

7

试一试

ggplot(df, aes(x = x, y = y),colour=val) +
  geom_tile(aes(fill = factor(val))) +
  facet_grid(. ~ facet_grid, scales = "free")+
  scale_fill_manual(labels=letters[1:4], values=c("red","blue","green","brown")) 

太好了,这对我有用。我也尝试过scale_fill_manual,但是在ggplot中我漏掉了颜色参数! - user969113

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接