如何使用ggplot2

时间:2017-08-03 14:42:51

标签: r ggplot2 boxplot smoothing

在ggplot2中给出一个像这样的框图:

ggplot(diamonds, aes(carat, price)) +
  geom_boxplot(aes(group = cut_width(carat, 0.25)), outlier.alpha = 0.1) +
  stat_smooth( method="lm", formula = y ~ poly(x,2), n= 40, se=TRUE, color="red", aes(group=1), size=1.5) 

我得到的图像如下:enter image description here

然而,stat_smooth线受每个克拉类别中的点数的影响很大。我宁愿平等对待每个类别,这意味着,在我看来,用特定的克拉值加权每个点,用该值的总点数的倒数。 (因此,在5点,该点的权重为1,在1处,该点的权重为1 / aBigNumber。)我已经尝试了权重美学到情节,但它打破了箱线图。我已经尝试将重量添加到光滑,但我收到错误:

  

错误:ggplot2不知道如何处理class uneval的数据

那么,如何对平滑函数进行加权以便对类别进行相等处理(与类别中的点数相反),并且仍然在输出中保留箱线图?

1 个答案:

答案 0 :(得分:2)

你可以这样做......

library(dplyr)
diamonds2 <- diamonds %>% mutate(cutcarat=cut_width(carat, 0.25)) %>% 
                          group_by(cutcarat) %>% 
                          summarise(carat=mean(carat), price=mean(price))
ggplot() +
      geom_boxplot(data=diamonds,
                   aes(x=carat, y=price, group = cut_width(carat, 0.25)), 
                   outlier.alpha = 0.1) +
      geom_smooth(data=diamonds2, 
                   aes(x=carat, y=price), method="lm", 
                   formula = y ~ poly(x,2), n= 40, se=TRUE, color="red", size=1.5)

enter image description here