首页 > 解决方案 > 图例中二维密度图从0变为1

问题描述

  1. 我的目的——如何将图例中的二维密度图从0变为1。
  2. 我在这里生成了两个可变序列数据。我已经使用 实现了二维密度图stat_density_2d,像这样
p <- ggplot(df, aes(x=spi,y=crop))+
  labs(title = "",y = "y", x = "x") +
  #geom_raster() +
  #geom_point() +
  stat_density_2d(geom ="raster",aes(fill = ..density..),contour = F)

在此处输入图像描述

但是,图例“密度”显示为 0.05 到 0.2。我想将“密度”标准化为 [0,1] 的区间,其中 1 表示最高密度,0 表示最低密度。我如何对其进行编程,或者我如何处理原始数据以获得我想要的结果。

标签: rggplot2

解决方案


这实际上很容易,您只需更改fill = ..density..fill = ..ndensity..(注意:现代用法是stat(ndensity))。

示例数据的默认密度:

ggplot(faithful, aes(eruptions, waiting)) +
  stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = F)

在此处输入图像描述

密度缩放到 [0-1] 范围:

ggplot(faithful, aes(eruptions, waiting)) +
  stat_density_2d(geom = "raster", aes(fill = stat(ndensity)), contour = F)

在此处输入图像描述

如果您明确希望在图例中包含 0:

ggplot(faithful, aes(eruptions, waiting)) +
  stat_density_2d(geom = "raster", aes(fill = stat(ndensity)), contour = F) +
  scale_fill_gradient(limits = c(0, NA))

这记录在 的“计算变量”下?stat_density_2d


推荐阅读