首页 > 解决方案 > 在这个例子中“折叠到唯一的‘x’值”是什么意思?

问题描述

下面的示例图会产生一个警告

In regularize.values(x, y, ties, missing(ties), na.rm = na.rm) :
  collapsing to unique 'x' values

而且我无法弄清楚这在我的示例中意味着什么。

它必须与 相关5,因为替换54或时警告消失1

df <- data.frame(x = 1, y = c(0, 0.25, 0.5, 0.75, 5))
ggplot2::ggplot(df, ggplot2::aes(x = x, y = y)) +
    ggplot2::geom_violin(draw_quantiles = c(0.5))

这里发生了什么?

标签: rggplot2uniquewarnings

解决方案


@teunbrand 证实了我的假设

ecdf <- stats::approxfun(dens, data$y) 

https://github.com/tidyverse/ggplot2/blob/cc3951cd942d/R/geom-violin.r#L200)是罪魁祸首。

density中的零data$y转换为累积密度中的相等值(“关系”)dens- 因此发出警告。

这些零点可以通过adjust密度的带宽来避免(这里,稍微 - 在我的示例中,我需要使用与 一样大的值3):

df <- data.frame(x = 1, y = c(0, 0.25, 0.5, 0.75, 5))
ggplot2::ggplot(df, ggplot2::aes(x = x, y = y)) +
    ggplot2::geom_violin(draw_quantiles = c(0.5), adjust=1.1)

注意:由于诸如dens用于累积密度之类的细节,该代码难以阅读。

stats::regularize.values不一定更好:

    x <- xy.coords(x, y) # -> (x,y) numeric of same length
    y <- x$y
    x <- x$x

该问题也可以通过

ecdf <- stats::approxfun(dens, data$y, ties = "ordered") 

就像在这个猴子补丁中一样:

create_quantile_segment_frame <- function(data, draw_quantiles) {
  dens <- cumsum(data$density) / sum(data$density)
  ecdf <- stats::approxfun(dens, data$y, ties = "ordered")
  ys <- ecdf(draw_quantiles) # these are all the y-values for quantiles

  # Get the violin bounds for the requested quantiles.
  violin.xminvs <- (stats::approxfun(data$y, data$xminv))(ys)
  violin.xmaxvs <- (stats::approxfun(data$y, data$xmaxv))(ys)

  # We have two rows per segment drawn. Each segment gets its own group.
  ggplot2:::new_data_frame(list(
    x = ggplot2:::interleave(violin.xminvs, violin.xmaxvs),
    y = rep(ys, each = 2),
    group = rep(ys, each = 2)
  ))
}
assignInNamespace("create_quantile_segment_frame", create_quantile_segment_frame, "ggplot2")

df <- data.frame(x = 1, y = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10))
ggplot2::ggplot(df, ggplot2::aes(x = x, y = y)) +
    ggplot2::geom_violin(draw_quantiles = c(0.5), bw = 0.1)

推荐阅读