【问题标题】:How to customize a boxplot legend indicating mean, outliers, median, etc?如何自定义指示均值、异常值、中值等的箱线图图例?
【发布时间】:2018-01-22 16:40:14
【问题描述】:

我有一个箱线图,根据我的主管的建议,我必须在图例中指出平均值、异常值和中位数,如下图所示:

我如何使用ggplot2 做到这一点?

library(ggplot2)

A <- 1:20
DF <- data.frame(A)

ggplot(data = DF) +
  geom_boxplot(aes(x = "", y = A))

【问题讨论】:

    标签: r ggplot2 customization legend boxplot


    【解决方案1】:

    没有直接的方法。但是您可以使用另一个图制作自定义图例:

    p <- ggplot(mtcars) +
      geom_boxplot(aes(x = factor(cyl), y = mpg))
    
    d1 <- data.frame(x = 1, y = c(1:1000, 1502))
    d2 <- data.frame(
      y = c(boxplot.stats(d1$y)$stats, 1502), 
      x = 1, 
      label = c('min', '1st quartile', 'median', '3rd quartile', 'max', 'outlier')
    )
    leg <- ggplot(d1, aes(x, y)) + geom_boxplot(width = 0.2) + 
      geom_text(aes(x = 1.15, label = label), d2, hjust = 0) +
      xlim(0.9, 1.5) +
      theme_void() + theme(panel.background = element_rect(fill = 'white', color = 1))
    
    p + annotation_custom(ggplotGrob(leg), xmin = 3, xmax = 3.5, ymin = 25, ymax = 35)
    

    【讨论】:

    • 不幸的是,它不包括叠加在箱线图上的“平均”点,但这似乎更容易手动添加。
    • 您可以添加到leg 情节中,随便玩一下。但是您的代码示例没有。
    猜你喜欢
    • 2023-03-12
    • 2021-01-21
    • 2020-08-21
    • 2021-11-06
    • 2020-05-04
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多