首页 > 解决方案 > ggplot stat_density2d can't plot contour with tile geoms

问题描述

Using contours with stat_density2d gives error:

ggplot(faithful, aes(x = eruptions, y = waiting, fill = ..density..)) + 
  stat_density2d(geom = "tile")

Don't know how to automatically pick scale for object of type function. Defaulting to continuous. Error in is.finite(x) : default method not implemented for type 'closure'

Using contour = F plots without error. What is the issue?

标签: rggplot2

解决方案


在 ggplot 中,geoms 和 stats 必须在添加到绘图的每一层中配对,因此如果您需要栅格/平铺和等高线,则需要进行两次调用:

library(ggplot2)

ggplot(faithful, aes(x = eruptions, y = waiting)) + 
    stat_density2d(aes(fill = ..density..), geom = "raster", contour = FALSE) + 
    stat_density2d()

如果您的目标是填充轮廓,那么不扩展 ggplot 真的很难。令人高兴的是,这已经在metR包中完成了:

ggplot(faithfuld, aes(eruptions, waiting, z = density)) + 
    metR::geom_contour_fill()

请注意,我切换到faithfuld,它已经计算了密度,因为geom_contour_fill像 一样geom_contour,旨在处理栅格数据。可能可以geom_contour_fill为您进行 2D 密度估计,但您自己调用MASS::kde2dstat_density2d使用什么)并将结果解压缩到适合geom_contour_fill.


推荐阅读