我在 ggplot2 中创建了一个图,然后在该图的“顶部”使用了 geom_rect() 来可视化(以红色显示)具有最低 10% 值的数据点z
。我仍然想使用 scale_fill_gradientn
来填充图例/比例尺,但我想在填充的最小值(即垂直比例的底部)插入红色。我如何使用 scale_fill_gradientn
并执行此操作?或者,如何使用其他方法达到预期的结果?
# The example code here produces an plot for illustrative purposes only.
# create data frame, from ggplot2 documentation
df <- expand.grid(x = 0:5, y = 0:5)
df$z <- runif(nrow(df))
# select min. 10%
df.1 <- df[df$z <= quantile(df$z, 0.1),]
#plot
ggplot(df, aes(x, y, fill = z)) + geom_raster() +
scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent") +
geom_rect(data=df.1, size=1, fill="red", colour=NA , aes(xmin=x-.5, xmax=x+.5, ymin=y-.5, ymax=y+.5))
最佳答案
一种解决方案是提供“red”
作为scale_fill_gradientn()
中的颜色之一。使用红色两次以确保在 0 到 0.1 范围内的所有值都变为“红色”,然后使用 seq()
使 0.1001 到 1 范围内的所有其他值均匀分布。在这种情况下,您不需要第二个数据框。
set.seed(123)
df <- expand.grid(x = 0:5, y = 0:5)
df$z <- runif(nrow(df))
ggplot(df, aes(x, y, fill = z)) + geom_raster() +
scale_fill_gradientn(colours=c("red","red",topo.colors(6)),
values=c(0,0.1,seq(0.1001,1,length.out=7)),na.value = "transparent")
关于r - 将颜色插入到ggplot2中指定位置/值的刻度填充渐变中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24264404/