【问题标题】:How to selectively map aesthetics (convex hulls) to ggplot2?如何选择性地将美学(凸壳)映射到ggplot2?
【发布时间】:2018-12-15 08:24:14
【问题描述】:

我正在尝试在嘈杂的数据上叠加凸包。我只想要主集群上的外壳(而不是红色异常值)。

如何在绘制所有点的同时绘制所有其他船体?

在我的解决方法尝试中,我不小心使所有异常值都消失了。此外,在 Shiny 应用程序中绘制我的实际数据时,形状 (21-25) 被扭曲了。

这个问题是通过在构建统计数据时修修补补,还是通过编辑映射来解决?

要求:我还想保留 ggplot2 的内容,因为这将全部包含在 ShinyApp 中,并且如果用户单击复选框,则会绘制外壳。每个图的集群数量各不相同,但第一个总是异常值。

数据生成

library(dbscan)
library(ggplot2)
data("DS3")
DS3_cl <- hdbscan(DS3, minPts = 25)
DS3_comb <- DS3
DS3_comb$cluster <- as.character(DS3_cl$cluster)

图形函数/参数

cols <- c('#e41a1c','#377eb8','#4daf4a','#984ea3','#ff7f00','#a65628','#f781bf','#999999','#ffff33') 
cols_2 <-  c(NA,'#377eb8','#4daf4a','#984ea3','#ff7f00','#a65628','#f781bf','#999999','#ffff33') 

StatChull <- ggproto("StatChull", Stat, 
                     compute_group = function(data, scales) {
                       data[chull(data$x, data$y), , drop = FALSE]
                     },
                     # Do the outlier removal around here?
                     required_aes = c("x", "y")
)

stat_chull <- function(mapping = NULL, data = NULL, geom = "polygon",
                       position = "identity", na.rm = FALSE, show.legend = NA, 
                       inherit.aes = TRUE, ...) {
  layer(
    stat = StatChull, data = data, mapping = mapping, geom = geom, 
    position = position, show.legend = show.legend, inherit.aes = inherit.aes,
    params = list(na.rm = na.rm, ...)
  )
}

地块

plot_1 <- ggplot(data = DS3_comb, aes(X, Y, color = cluster)) + 
  geom_point(alpha = 0.4) + 
  scale_color_manual(values = cols) +
  theme_bw()

plot_2 <- plot_1 + stat_chull(fill = NA)

解决方法尝试:

plot_3 <- ggplot(data = DS3_comb, aes(X,Y, fill = cluster, color = cluster)) +
  geom_point(shape = 21, alpha = 0.4) +
  scale_fill_manual(values = cols) +
  scale_color_manual(values = cols_2) +
  theme_bw()

咨询的来源:

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    只需对该层的数据进行子集化。例如

    plot_1 + stat_chull(fill = NA, data=subset(DS3_comb,cluster!=0))
    

    【讨论】:

    • ...我想多了。这也适用于 ShinyApp 刷点!
    • 嘿@MrFlick,我试图让颜色依赖于闪亮的输入。 stat_chull() 不会随着颜色的变化而变化,除非我去掉了子集选项。我尝试通过重新指定颜色来重新指定船体映射,但这没有用。你能为我指出正确的方向吗?如果我的问题太具体/太复杂,我会尽快用一个最小的例子来更新这篇文章
    • @ADuv 不要更新这篇文章。这个问题已经回答了。如果您有新问题,请开始新帖子。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    相关资源
    最近更新 更多