【问题标题】:Adjusting x limits xlim() in ggplot2 geom_density() to mimic ggvis layer_densities() behavior调整 ggplot2 geom_density() 中的 x 限制 xlim() 以模仿 ggvis layer_densities() 行为
【发布时间】:2015-02-24 14:48:55
【问题描述】:

有没有办法让 ggplot2 的 geom_density() 函数模仿 ggvis 的 layer_densities() 的行为?也就是说,在不调用xlim() 的情况下,让它看起来像p3(见下文)吗?具体来说,我更喜欢平滑密度曲线尾部的视图。

library(ggvis)
library(ggplot2)

faithful %>% 
  ggvis(~waiting) %>% 
  layer_densities(fill := "green") -> p1

ggplot(faithful, aes(x = waiting)) +
  geom_density(fill = "green", alpha = 0.2) -> p2

ggplot(faithful, aes(x = waiting)) +
  geom_density(fill = "green", alpha = 0.2) +
  xlim(c(30, 110)) -> p3

p1
p2
p3

ggvis 输出:

ggplot2“默认”:

ggplot2“所需”:

注意:可以通过以下方式使 ggvis 模仿 ggplot2(使用 trim=TRUE),但我想换个方向......

faithful %>% 
  compute_density(~waiting, trim=TRUE) %>% 
  ggvis(~pred_, ~resp_) %>% 
  layer_lines()

【问题讨论】:

  • 为什么要避免 xlim 参数?您是否担心解决方案不够通用?
  • @RomanLuštrik 正确 - 我正在寻找更通用的解决方案。

标签: r ggplot2 ggvis


【解决方案1】:

如何调用xlim,但限制是通过编程定义的?

l <- density(faithful$waiting)
ggplot(faithful, aes(x = waiting)) +
  geom_density(fill = "green", alpha = 0.2) +
  xlim(range(l$x))

缺点是双密度估计,所以请记住这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-03-21
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多