代码之家  ›  专栏  ›  技术社区  ›  Jaken

使用scale_*_steps进行合并时避免重新缩放

  •  1
  • Jaken  · 技术社区  · 4 月前

    我有连续的数据,我想用分箱色阶显示。由于数据分布不均,我希望在频谱的低端有更多的中断,以强调低值的差异。然而,在合并过程中,scale_fill_stepsn似乎会自动重新缩放数据(请参阅有关重新缩放器的注释 here )从而调色板反映了断点的相对位置。这使得低值的差异难以区分。我想让调色板均匀地分布在我定义的断点上。在仍然使用scale_ill_stepsn()的情况下,有什么方法可以做到这一点吗?

    我知道我可以手动将数据分类,然后将其作为离散数据传递给ggplot,但我想避免这种情况。我还想避免对数据进行任何转换(例如获取日志)。

    library(ggplot2)
    
    #generate sample data with outliers
    df <- expand.grid(x = 0:5, y = 0:5)
    df$z <- abs(rnorm(36))
    df$z[[4]] <- 12
    df$z[[8]] <- 17
    df$z[[30]] <- 7
    breaks=c(0, 0.25, 0.5, 1, 2, 5, 10, 20)
    
    ggplot(df) +
      geom_tile(aes(x=x, y=y, fill=z)) + 
      scale_fill_stepsn(colors=terrain.colors(7),
                        breaks=breaks)
    

    ggplot figure showing tiles; most of the tiles are very similar shades of green

    1 回复  |  直到 4 月前
        1
  •  2
  •   stefan    4 月前

    您可以使用 values= 参数指定如何重新缩放数据,即根据文档:

    如果颜色不应沿梯度均匀分布,则该向量给出了颜色向量中每种颜色的位置(在0和1之间)。

    library(ggplot2)
    set.seed(123)
    
    breaks <- c(0, 0.25, 0.5, 1, 2, 5, 10, 20)
    
    ggplot(df) +
      geom_tile(aes(x = x, y = y, fill = z)) +
      scale_fill_stepsn(
        colors = terrain.colors(7),
        breaks = breaks,
        values = scales::rescale(breaks),
        limits = range(breaks)
      )
    

    enter image description here

    推荐文章