繁体   English   中英

在 R 中使用 ggplot2,如何在各自的点上打印 min、q1、mean、median、q3、max 值?

[英]Using ggplot2 in R, how can I also print min, q1, mean, median, q3, max values on their respective points?

我已经能够打印异常值。

ggplot(mtcars) +
  aes(x = "", y = wt) +
  geom_boxplot() +
  geom_text(data=. %>% 
            mutate(type=rownames(.)) %>% 
            filter(wt %in% boxplot.stats(wt, coef=1.4)$out),
            aes(label=type,y=wt), 
            nudge_x=0.01, colour="red", size=3, hjust=0) +    
theme_classic()

我知道 ggplotly 函数会显示此信息,但它不允许与图像一起保存。 @Sparhawk 和 @CuriousJ 使用 boxplot 函数提出了类似的解决方案。

我试过这种方式,但无济于事。

ggplot(mtcars) +
  aes(x = "", y = wt) +
  geom_boxplot() +
  geom_text(data=. %>% 
            mutate(type=rownames(.)) %>% 
            filter(wt %in% boxplot.stats(wt, coef=1.4)$out),
            aes(label=type,y=wt), 
            nudge_x=0.01,size=3, hjust=0) +  
  geom_text(data=mtcars, aes(
                             label=boxplot.stats(wt)$start,
                             y=boxplot.stats(wt)$start), 
            nudge_x=0.01, size=3, hjust=0) + 
theme_classic()

知道如何解决这个问题吗?

q1 /中值 / q3 没有点(这些是汇总统计数据,而不是单个点),但是如果您想在图上包含相应的值(最小值、q1、中值、q3、最大值),您可以使用:

library(tidyverse)

boxplot_labels <- tibble(y = boxplot.stats(mtcars$wt, coef=1.4)$stats,
                                 x = c(1.1, 1.5, 1.5, 1.5, 1.1)) %>% 
  mutate(labels = paste("\u2190 y =", y))

ggplot(mtcars) +
  aes(x = "", y = wt) +
  geom_boxplot() +
  geom_text(data=. %>% 
              mutate(type=rownames(.)) %>% 
              filter(wt %in% boxplot.stats(wt, coef=1.4)$out),
            aes(label=type,y=wt), 
            nudge_x=0.01, colour="red", size=3, hjust=0) +
  geom_text(data = boxplot_labels,
            aes(x = x, y = y, label = labels), color = "red") +
  theme_classic()

reprex 包( v2.0.0 ) 于 2021 年 7 月 20 日创建

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM