【问题标题】:Rearrange facets as per median of the boxplot根据箱线图的中位数重新排列构面
【发布时间】:2016-09-18 01:32:12
【问题描述】:

使用数据集 mpg,我能够绘制城市 mpg、高速公路 mpg 和类模型之间的三向关系。我使用以下代码(使用 ggplot2)输出附件Boxplot.png 中显示的图形。

ggplot(mpg,aes(cty,hwy))+
  aes(color=class)+
  geom_boxplot()+
  facet_grid(.~class, scales='free')+
  theme(axis.text.x = element_text(angle = -90, vjust = 1, hjust = 0))+
  scale_x_continuous('City mpg')+
  scale_y_continuous('Highway mpg')+
  theme(legend.position="none")

问题:

  1. 我想按中位数递增的顺序显示箱线图。我该怎么做?

  2. 我可以在每个箱线图的顶部显示中值吗?

【问题讨论】:

    标签: r ggplot2 boxplot median facet


    【解决方案1】:
    require(ggplot2)
    
    aggregate(mpg$hwy, by=list(mpg$class), median)
    
    mpg$class <- factor(mpg$class, levels = c("compact", "midsize", "subcompact",
                                              "2seater", "minivan", "suv", "pickup"))
    
    ggplot(mpg,aes(cty,hwy))+
      aes(color=class)+
      geom_boxplot()+
      facet_grid(.~class, scales='free')+
      theme(axis.text.x = element_text(angle = -90, vjust = 1, hjust = 0))+
      scale_x_continuous('City mpg')+
      scale_y_continuous('Highway mpg')+
      theme(legend.position="none")
    

    您还可以显示中位数。这是一个很好的解释/示例:

    How to display the median value in a boxplot in ggplot?

    例子是:

    library(plyr)
    library(ggplot2)
    
    p_meds <- ddply(p, .(TYPE), summarise, med = median(TOTALREV))
    
    ggplot(p,aes(x = TYPE, y = TOTALREV)) + 
        geom_boxplot() + 
        geom_text(data = p_meds, aes(x = TYPE, y = med, label = med), 
                  size = 3, vjust = -1.5)
    

    【讨论】:

      【解决方案2】:

      我经常做的是使class 变量成为一个因素,其中级别按您想要的顺序排列。这样,您的构面图将按您的意愿排序。

      为了在顶部显示中值,我经常重新定义class 变量,例如compact (med = 26)

      【讨论】:

      • 包含代码的答案更符合本网站的要求。 Handwaving ^H^H^H^H^Huntested 解决方案价值不大。
      猜你喜欢
      • 2021-12-25
      • 2016-11-03
      • 1970-01-01
      • 2011-04-15
      • 2020-06-01
      • 2023-03-25
      • 2023-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多