r - 二维图中一维的ggplot2密度

标签 r ggplot2 plot

我想绘制一个背景,以捕捉散点图中一维点的密度。这将起到与边际密度图或地毯图类似的作用。我有一种方法不是特别优雅,我想知道是否有一些内置功能可以用来制作这种情节。

目前的做法主要有几个问题:

  • 边界处的 Alpha 重叠会导致较低分辨率的 strip ,如此处所示。 - 主要目标,寻找一个 geom 或其他解决方案,绘制一个漂亮的连续带,填充特定颜色。类似 geom_density_2d() 的东西,但统计数据仅从 X 轴绘制。
  • “背景”不覆盖扩展区域,可以使用 coord_cartesian(expand = FALSE) 但希望覆盖常规边距。 - 没什么大不了的,但不是必需的。
  • 设置 scale_fill 会“消耗”绘图的选项,不允许为点本身单独设置。 - 这可能不容易实现,图层的独立调色板似乎是 ggplot2 的一个基本问题。
data(iris)

dns <- density(iris$Sepal.Length)
dns_df <- tibble(
        x = dns$x,
        density = dns$y
    )%>%
        mutate(
            start = x - mean(diff(x))/2,
            end = x + mean(diff(x))/2
        )

ggplot() +
    geom_rect(
        data = dns_df, 
        aes(xmin = start, xmax = end, fill = density),
        ymin = min(iris$Sepal.Width),
        ymax = max(iris$Sepal.Width),
        alpha = 0.5) +
    scale_fill_viridis_c(option = "A") +
    geom_point(data = iris, aes(x = Sepal.Length, y = Sepal.Width)) +
    geom_rug(data = iris, aes(x = Sepal.Length))

ggplot 1d density example

最佳答案

这是一个有点棘手的解决方案,因为它(滥用)使用对象如何在内部参数化的知识来获得你想要的东西,这会产生一些警告,但得到你想要的东西。

首先,我们将使用 geom_raster() + stat_density() 装饰一些选择 after_stat()/stage () 延迟求值。通常,这会导致 height = 1 strip,但是通过将内部参数 ymin/ymax 设置为不定式,我们将使 strip 延伸整个高度阴谋。使用 geom_raster() 可以解决您遇到的 alpha 问题。

library(ggplot2)

p <- ggplot(iris) +
  geom_raster(
    aes(Sepal.Length,
        y = mean(Sepal.Width),
        fill = after_stat(density),
        ymin = stage(NULL, after_scale = -Inf),
        ymax = stage(NULL, after_scale = Inf)),
    stat = "density", alpha = 0.5
  )
#> Warning: Ignoring unknown aesthetics: ymin, ymax
p
#> Warning: Duplicated aesthetics after name standardisation: NA

接下来,我们添加一个填充比例,紧接着是 ggnewscale::new_scale_fill()。这允许另一层使用第二个填充比例,如 fill = Species 所示。

p <- p +
  scale_fill_viridis_c(option = "A") +
  ggnewscale::new_scale_fill() +
  geom_point(aes(Sepal.Length, Sepal.Width, fill = Species),
             shape = 21) +
  geom_rug(aes(Sepal.Length))
p
#> Warning: Duplicated aesthetics after name standardisation: NA

最后,为了摆脱 x 轴的填充,我们可以手动扩展限制,然后在扩展中收缩。它允许估计密度的扩展范围,使栅格填充整个区域。 ggplot2 和 scales::expand_range() 的参数化方式之间存在一些不匹配,因此确切的值需要反复试验。

p +
  scale_x_continuous(
    limits = ~ scales::expand_range(.x, mul = 0.05),
    expand = c(0, -0.2)
  )
#> Warning: Duplicated aesthetics after name standardisation: NA

reprex package 创建于 2022-07-04 (v2.0.1)

关于r - 二维图中一维的ggplot2密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72851781/

相关文章:

r - 如果 dplyr 中满足条件,则直接对行进行条件求和

r - R中非列表类的继承?

r - Google Sheets 拟合模型是否是检索 nls() 起始参数的有效位置?

r - 如何在 R 中使用 plotly 在时间序列中绘制多个系列/线?

matlab - 在 Matlab 中绘制大型数据集

r - R 中的多项式回归(二阶)图

R- 合并 3 个或更多数据帧

R - ggplot 上的背景颜色沿对角线分割?

r - 如何在 ggplot2 中将图例键字形的形状更改为六边形?

r - plot.new() 中的错误 : figure margins too large, 散点图