【问题标题】:Weighted ggplot2 warning: Ignoring unknown aesthetics: weight加权ggplot2警告:忽略未知的美学:重量
【发布时间】:2017-12-01 11:15:43
【问题描述】:

我尝试用 ggplot2 绘制加权密度。结果似乎很好,但我收到以下警告:Warning: Ignoring unknown aesthetics: weightother ggplot2 applications 中似乎出现了类似的问题,因此我想知道是否可以忽略警告。

可重现的例子:

library(ggplot2)

set.seed(123)

# Some random data & weights
x <- rnorm(1000, 5)
w <- x^5

# Plot unweighted
ggplot() + stat_density(aes(x = x))

# Plot weighted - Warning: Ignoring unknown aesthetics: weight
ggplot() + stat_density(aes(x = x, weight = w / sum(w))) # Weighting seems to work fine

# Comparison of weighted density in base graphics - Same results as with ggplot2
plot(density(x, weights = w / sum(w)))

可以忽略此警告消息吗?

【问题讨论】:

  • 你可以试试options(warn=-1)? (source)
  • @h3rm4n 你永远不应该那样做。如果需要,请使用suppressWarnings。无论如何,这应该提交给 ggplot2 错误跟踪器(如果尚未提交)。
  • @h3rm4n 我不在乎是否显示警告,我只是想确保我的结果是正确的。
  • @Roland 什么是“ggplot2 错误跟踪器”,我在哪里可以找到它?即使我收到警告消息,您是否同意我的结果有效?
  • @Roland 为什么会这样?出于链接源中提到的原因?

标签: r ggplot2 plot warnings


【解决方案1】:

你可以使用geom_density来避免警告:

ggplot() + 
  geom_density(aes(x = x, weight = w / sum(w)), color = "green") +
  geom_density(aes(x = x), color = "blue")

我本来希望 stat_ 函数能够处理与 geom 相同的美学效果,而且它似乎确实如此。然后警告将是一个应该报告给维护人员的错误。

【讨论】:

  • 谢谢,是的,似乎 stat_ 也有效,但 geom_ 似乎更可取!
【解决方案2】:

这是另一个解决方案:

ggplot(data=NULL, aes(x = x, weight=w/sum(w))) + stat_density() 

还有:

ggplot(data=NULL, aes(x = x, weight=w/sum(w))) + 
   stat_density(fill=NA, color = "green") + 
   stat_density(aes(x=x), fill=NA, color = "blue", inherit.aes=F)

【讨论】:

    【解决方案3】:

    您是否收到警告似乎取决于您给出 weight 参数的位置(ggplot2 版本 2.2.1):

    按照这些答案: Create weighted histogram, Histogram with weights

    设置数据:

    w = seq(1,1000)
    v = sort(runif(1000))
    foo = data.frame(v,w)
    

    以下命令产生警告:

    ggplot(foo) + geom_histogram(aes(v, weight=w),bins = 30)
    

    这些命令不会产生警告:

    ggplot(foo, aes(v, weight=w)) + geom_histogram(bins = 30)
    ggplot(foo, aes(weight=w)) + geom_histogram(aes(v),bins = 30)
    

    但是所有三个命令都会产生相同的情节。

    【讨论】:

    • 感谢您的澄清!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2023-04-02
    相关资源
    最近更新 更多