我很难为我的2个不同的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")
Run Code Online (Sandbox Code Playgroud)
我正在使用scale_fill_gradient函数brewer.pal功能来覆盖使用的标准颜色.但是,我想要实现的是在两个不同的facet_grids中设置1应该使用相同颜色(grey30)的值.例如,对于第一个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")) +
Run Code Online (Sandbox Code Playgroud)
第一个ggplot给了我几乎我想要的东西.两种不同的facet_grids中有4种不同的颜色.我尝试用来scale_fill_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"))
Run Code Online (Sandbox Code Playgroud)