我按了this链接,尝试
以下代码
library(reshape2)
library(ggplot2)
library(scales)
ran <- matrix(nrow = 3, ncol = 2, c(-2,-1,0,1,2,3))
ran_melt <- melt(ran)
ggplot(ran_melt, aes(Var1, Var2)) +
geom_tile(aes(fill = value), color = "white") +
scale_fill_gradientn(colours = c("red", "white", "blue"),
values = rescale(c(min(ran_melt$value), 0, max(ran_melt$value)))) +
labs(fill = 'legend')
将绘制此
如果我将max(ran_melt$value)
更改为2
:
ggplot(ran_melt, aes(Var1, Var2)) +
geom_tile(aes(fill = value), color = "white") +
scale_fill_gradientn(colours = c("red", "white", "blue"),
values = rescale(c(min(ran_melt$value), 0, 2))) +
labs(fill = 'legend')
那么我怎样才能实现我的两个目标呢?
答案 0 :(得分:2)
您可以在limits
中使用参数oob
和scale_fill_gradientn
来实现您的目标:
ggplot(ran_melt, aes(Var1, Var2)) +
geom_tile(aes(fill = value), color = "white") +
scale_fill_gradientn(
colours = c("red", "white", "blue"),
limits = c(-2, 2),
oob = squish) +
labs(fill = 'legend')
说明:oob = squish
为limits
以外的值提供与limits
的最小值/最大值相同的颜色/填充值。参见例如有关?scale_fill_gradientn
的详细信息,请oob
。
如果您有非对称limits
,则可以将参数values
与rescale
一起使用:
ggplot(ran_melt, aes(Var1, Var2)) +
geom_tile(aes(fill = value), color = "white") +
scale_fill_gradientn(
colours = c("red", "white", "blue"),
limits = c(-1, 2),
values = rescale(c(-1, 0, 2)),
oob = squish) +
labs(fill = 'legend')