如何在ggplot2中限制调色板
How to constrain the colorpalette in ggplot2
从下图中,我想将从绿色到红色(黄色部分)的过渡限制在红线处。我希望 z<1 时为绿色,z>1 时为红色,黄色以 z=1 为中心。
library(ggplot2)
数据(只是为了说明情节所必需的)
x=seq(0,5,length=1e2)
y=seq(0,5,length=1e2)
#
df=expand.grid(x=x,y=y)
df$z=df$x*df$y
情节
ggplot(data=df, aes(x=x,y=y,z=z,fill=z)) +
geom_raster()+
stat_contour(breaks=1, size=1, colour="red") +
scale_fill_gradientn (colours=colorRampPalette (c ("green", "yellow","red")) (20))
感谢您的帮助
这是创建情节的一种方法。正如@CMichael 指出的那样,可以使用函数 scale_fill_gradient2
。它允许指定基于三种颜色的连续色标。
ggplot(data=df, aes(x = x, y = y, z = z, fill = z)) +
geom_raster() +
stat_contour(breaks = 1, size = 1, colour = "red") +
scale_fill_gradient2(low = "green", mid = "yellow", high = "red", midpoint = 1)
从下图中,我想将从绿色到红色(黄色部分)的过渡限制在红线处。我希望 z<1 时为绿色,z>1 时为红色,黄色以 z=1 为中心。
library(ggplot2)
数据(只是为了说明情节所必需的)
x=seq(0,5,length=1e2)
y=seq(0,5,length=1e2)
#
df=expand.grid(x=x,y=y)
df$z=df$x*df$y
情节
ggplot(data=df, aes(x=x,y=y,z=z,fill=z)) +
geom_raster()+
stat_contour(breaks=1, size=1, colour="red") +
scale_fill_gradientn (colours=colorRampPalette (c ("green", "yellow","red")) (20))
感谢您的帮助
这是创建情节的一种方法。正如@CMichael 指出的那样,可以使用函数 scale_fill_gradient2
。它允许指定基于三种颜色的连续色标。
ggplot(data=df, aes(x = x, y = y, z = z, fill = z)) +
geom_raster() +
stat_contour(breaks = 1, size = 1, colour = "red") +
scale_fill_gradient2(low = "green", mid = "yellow", high = "red", midpoint = 1)