[英]ggplot stat_density2d can't plot contour with tile geoms
Using contours with stat_density2d
gives error: 将轮廓与stat_density2d
一起使用stat_density2d
产生错误:
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' is.finite(x)中的错误:类型“ closure”未实现默认方法
Using contour = F
plots without error. 使用contour = F
曲线无误差。 What is the issue? 有什么问题
In ggplot, geoms and stats must be paired in each layer added to the plot, so if you want both rasters/tiles and contour lines, you need to make two calls: 在ggplot中,几何图形和统计数据必须在添加到图形中的每一层中配对,因此,如果您既需要栅格/平铺图又需要轮廓线,则需要进行两次调用:
library(ggplot2)
ggplot(faithful, aes(x = eruptions, y = waiting)) +
stat_density2d(aes(fill = ..density..), geom = "raster", contour = FALSE) +
stat_density2d()
If you're aiming instead for filled contours, it's really hard without extending ggplot. 如果您要瞄准填充轮廓,那么不扩展ggplot确实很难。 Happily, that has already been done in the metR package: 幸运的是,这已经在metR软件包中完成了:
ggplot(faithfuld, aes(eruptions, waiting, z = density)) +
metR::geom_contour_fill()
Note that I switched to faithfuld
, which already has the density computed, as geom_contour_fill
, like geom_contour
, is designed to work with raster data. 请注意,我切换到faithfuld
,已经有计算密度,如geom_contour_fill
,像geom_contour
,被设计成栅格数据的工作。 It may be possible to get geom_contour_fill
to do the 2D density estimation for you, but it may be more straightforward to call MASS::kde2d
(what stat_density2d
uses) yourself and unpack the results to a data frame suitable for geom_contour_fill
. 可能可以让geom_contour_fill
为您进行2D密度估算,但是您自己调用MASS::kde2d
( stat_density2d
使用什么)并将结果解压缩到适合geom_contour_fill
的数据框中可能更直接。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.