加权 ggplot2 警告:忽略未知美学:权重

Weighted ggplot2 warning: Ignoring unknown aesthetics: weight

我尝试使用 ggplot2 绘制加权密度。结果似乎很好,但我收到以下警告:Warning: Ignoring unknown aesthetics: weight。类似的问题似乎出现在 other 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)))

是否可以忽略此警告消息?

您可以使用 geom_density:

来避免警告
ggplot() + 
  geom_density(aes(x = x, weight = w / sum(w)), color = "green") +
  geom_density(aes(x = x), color = "blue")

我原以为 stat_ 函数可以处理与 geom 相同的美学,而且它似乎确实如此。警告将是一个应该报告给维护者的错误。

这是另一个解决方案:

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)

您是否收到警告似乎取决于您在何处提供权重参数(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)

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