【问题标题】:ggplot stat_density2d can't plot contour with tile geomsggplot stat_density2d 无法使用平铺几何图形绘制轮廓
【发布时间】:2019-05-04 06:42:26
【问题描述】:

使用带有stat_density2d 的轮廓会出错:

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

不知道如何为对象类型自动选择比例 功能。默认为连续。 is.finite(x) 中的错误:默认 没有为“闭包”类型实现方法

使用contour = F 绘制没有错误。问题是什么?

【问题讨论】:

  • 在文档here 中,在stat_density_2d(geom = "raster", aes(fill = stat(density)), contour = FALSE) 之前有一个注释# If we turn contouring off, we can use use geoms like tiles。不过,我不清楚为什么。
  • 要绘制轮廓,您需要中断,而瓷砖/栅格是连续的。一个 stat/geom 永远不会绘制超过一个 geom,所以如果你想要颜色和线条,请拨打两个电话。 (第二行,所以它们会在最上面。)如果你想要填充的行,请查看 metR 包,它以这种方式做了一些非常酷的事情。
  • @alistaire 你能发帖回答吗?

标签: r ggplot2


【解决方案1】:

在 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_fillgeom_contour 一样,旨在处理栅格数据。可以让geom_contour_fill 为您进行 2D 密度估计,但您自己调用MASS::kde2dstat_density2d 使用的内容)并将结果解包到适合geom_contour_fill 的数据框可能更直接.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多