R 不同平面网格的不同颜色

R 不同平面网格的不同颜色,r,colors,ggplot2,R,Colors,Ggplot2,我很难为我的两个不同的平面网格获得不同的颜色 以下是我的简单示例: 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 =

我很难为我的两个不同的平面网格获得不同的颜色

以下是我的简单示例:

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")
第一个情节给了我几乎我想要的。两个不同的平面网格中有4种不同的颜色。我尝试使用
scale\u fill\u identity
更改4种颜色,但我在绘图中得到的是4种不同的颜色黑色/白色和红色/绿色,而不是上面指定的颜色。

试试这个

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")) 

太好了,这对我很有效。我也在尝试缩放填充手册,但是,我错过了ggplot中的颜色参数!
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"))