【问题标题】:ggplot2 Boxplot displays different median than calculatedggplot2 Boxplot 显示的中位数与计算的不同
【发布时间】:2020-06-09 11:50:41
【问题描述】:

我正在根据大数据(2150000 例)绘制两组体重的简单箱线图。 除了去年的最后一组之外,所有组的中位数都相同,但在箱线图上,它的绘制方式与其他组相同。

 #boxplot
ggplot(dataset, aes(x=Year, y=SUM_MME_mg, fill=GenderPerson)) + 
  geom_boxplot(outlier.shape = NA)+
  ylim(0,850)


#median by group
pivot <- dataset %>%
  select(SUM_MME_mg,GenderPerson,Year )%>%
  group_by(Year, GenderPerson) %>%
  summarise(MedianValues = median(SUM_MME_mg,na.rm=TRUE))

我无法弄清楚我做错了什么,或者哪些数据在箱线图计算或中值函数中更准确。 R 不返回错误或警告。

 #my data:
> dput(head(dataset[,c(1,7,10)]))
structure(list(GenderPerson = c(2L, 1L, 2L, 2L, 2L, 2L), Year = c("2015", 
"2014", "2013", "2012", "2011", "2015"), SUM_MME_mg = c(416.16, 
131.76, 790.56, 878.4, 878.4, 878.4)), row.names = c(NA, 6L), class = "data.frame")

【问题讨论】:

    标签: r ggplot2 dplyr boxplot median


    【解决方案1】:

    这种行为的原因与ylim() 的运作方式有关。 ylim()scale_y_continuous(limits=... 的便利函数/包装器。如果您 look into the documentation 使用 scale_continuous 函数,您会发现设置限制不仅会放大某个区域,而且实际上也会删除该区域之外的所有数据点。这发生在计算/统计函数之前,所以这就是为什么使用ylim() 时中位数不同的原因。您在“外部”ggplot() 的计算采用了整个数据集,而使用 ylim() 意味着在进行计算之前删除了数据点。

    幸运的是,有一个简单的解决方法,即使用coord_cartesian(ylim=...) 代替ylim(),因为coord_cartesian() 只会放大数据而不删除数据点。看看这里的区别:

    ggplot(dataset, aes(x=Year, y=SUM_MME_mg, fill=GenderPerson)) + 
      geom_boxplot(outlier.shape = NA) + ylim(0,850)
    

    ggplot(dataset, aes(x=Year, y=SUM_MME_mg, fill=GenderPerson)) + 
      geom_boxplot(outlier.shape = NA) + coord_cartesian(ylim=c(0,850))
    

    这种行为的提示也应该很明显,第一个使用ylim() 的代码块也应该给你一个警告消息:

    Warning message:
    Removed 3 rows containing non-finite values (stat_boxplot). 
    

    而第二个使用coord_cartesian(ylim= 则没有。

    【讨论】:

    • 感谢您的帮助。
    • 谢谢!在我的案例中,这个问题也很难追踪。
    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 2018-09-21
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    相关资源
    最近更新 更多