r - 将颜色插入到ggplot2中指定位置/值的刻度填充渐变中

标签 r ggplot2 fill

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

enter image description here

关于r - 将颜色插入到ggplot2中指定位置/值的刻度填充渐变中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24264404/

相关文章:

r - 使用 roxygen2 记录 Rcpp 模块公开的方法

R: 'spatialSign' 函数对于识别异常值有用吗?

javascript - 在 R Shiny 的渲染 UI 中创建分类 sliderInput

r - 在同一面板中为每个组绘制单独的线性和二次回归图

r - 在 R : Computation failed in `stat_density2d()` : bandwidths must be strictly positive 中使用 geom_密度_2d() 时出错

r - 如何将 is.na 函数与日期一起使用

python - 在 Python 中使用 Rpy2 对具有翻转坐标的 ggplot2 条形图进行排序

python - pandas:在(多索引)DataFrame上使用每个组中最常见的值执行 fillna() 的最佳方法是什么?

ios - 如何使用 UIBezierPath 填充自定义形状

c# - 洪水填充递归算法