【问题标题】:ggplot2: Add contour labels to kernel density plot produced with geom_density_2dggplot2:将等高线标签添加到使用 geom_density_2d 生成的内核密度图中
【发布时间】:2021-11-14 15:47:00
【问题描述】:

有没有办法在 ggplot2 中使用geom_density_2d 制作的二维核密度图添加等高线标签?

library(ggplot2)

# load data
data("meuse")

# plot
ggplot(meuse, aes(x=x, y=y)) +
  geom_density_2d()

我尝试从构建的 ggplot 对象中提取绘制的数据,以便我可以将它从metR传递给geom_text_contour,但它返回的数据是一组用于绘制等高线的点,而不是 x 的网格/y 坐标 geom_text_contour 需要。

# extract denisty 2d
data <- ggplot_build(p)$data[[1]]
p + geom_path(data=data, 
              mapping=aes(color=nlevel, group=group), 
              color='red')

我想做这样的事情(这个例子来自geom_text_contour documentation)。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    据我所见,geom_text_contour 需要一个 geom_contour 统计数据,而这又需要一个类似栅格的对象,而不是您在此处的点集合。但是,有一个可以与geom_density_2d 一起使用的“directlabels”库。这个例子超级难看,但希望能帮助你入门!我更改了轴比例以使轮廓值更易于管理。

    library(directlabels)
    
    g1 <- ggplot(meuse %>% mutate(x=x/1000, y=y/1000), aes(x=x, y=y)) +
      geom_density_2d(aes(colour = ..level..))
    
    direct.label(g1, list(top.pieces, colour = 'black'))
    

    【讨论】:

      猜你喜欢
      • 2021-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      • 1970-01-01
      相关资源
      最近更新 更多