r - 如何使用 ggplot2 和 geom_tile 创建自定义色标?

标签 r ggplot2

我想修改颜色渐变以匹配一组预定义的阈值/切点和颜色。我怎样才能做到这一点?

截止值:-0.103200、0.007022、0.094090、0.548600
颜色:“#EDF8E9”、“#BAE4B3”、“#74C476”、“#238B45”

    #Create sample data

        pp <- function (n,r=4) {
              x <- seq(-r*pi, r*pi, len=n)
              df <- expand.grid(x=x, y=x)
              df$r <- sqrt(df$x^2 + df$y^2)
              df$z <- cos(df$r^2)*exp(-df$r/6)
              df
            }

            pp(20)->data

#create the plot

library(ggplo2)
            p <- ggplot(pp(20), aes(x=x,y=y))
            p + geom_tile(aes(fill=z))

#Generate custom colour ramp

library(RColorBrewer)

cols <- brewer.pal(4, "Greens")

最佳答案

你可以试试 scale_fill_brewer .首先,将您的 z 值装箱:

df <- pp(20)
df$z_bin <- cut(df$z, breaks = c(-Inf, -0.103200, 0.007022, 0.094090, 0.548600))

阴谋:
ggplot(data = df, aes(x = x, y = y, fill = z_bin)) +
  geom_tile() +
  scale_fill_brewer(palette = "Greens")

enter image description here

关于r - 如何使用 ggplot2 和 geom_tile 创建自定义色标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26103140/

相关文章:

r - ggplot2:从图中删除未使用的因子水平组合的方面 (facet_grid)

r - 在ggplot2中切断密度图

r - ggplot2 错误 : Mapping a variable to y and also using stat ="bin". 来自 'Elegant Graphics for Data Analysis' 的示例

r - par(mfcol=c(2,1)) 和空白第二行

R - (Tidyverse) 将多个观测值压缩为一个

r - 从一列数据帧中提取数据帧(tidyverse 方法)

r - 通过使用 dplyr 在列中查找术语来分组

r - 在 R 中绘制世界地图

r - 无法让 alpha 与 ggplot2::geom_sf 在 sf linestring 对象上一起使用

r - 使用 ggplot 绘制非线性回归列表