R可以在ggplot2中显示计算出的箱线图值作为标签吗?

问题描述 投票:0回答:1

如标题所说,ggplot2可以将计算出的箱线图值显示为标签吗?我想要显示最大值、上铰链、中值、下铰链和最小值。

用简单的例子:

ggplot()+
  geom_boxplot(data = mtcars,
               aes(group = cyl,
                   x = gear, y = mpg))

boxplot of mtcars

我知道我可以用如下简单的方法来计算这些值,并调用计算值来获得下图,但我的数据要复杂得多,很难计算这些值。

mtcarsProbs <- mtcars %>%
  group_by(cyl) %>%
  summarise(min = quantile(mpg, probs = 0),
            `25th` = quantile(mpg, probs = 0.25),
            median = quantile(mpg, probs = 0.5),
            `75th` = quantile(mpg, probs = 0.75),
            max = quantile(mpg, probs = 1))

ggplot()+
  geom_boxplot(data = mtcars,
               aes(group = cyl,
                   x = cyl, y = mpg))+
  geom_text(data = mtcarsProbs,
            aes(x = cyl, y = max+1,
                label = max))+
  geom_text(data = mtcarsProbs,
            aes(x = cyl, y = `75th`-0.5,
                label = `75th`))+
  geom_text(data = mtcarsProbs,
            aes(x = cyl, y = median+0.5,
                label = median))+
  geom_text(data = mtcarsProbs,
            aes(x = cyl, y = `25th`+0.5,
                label = `25th`))+
  geom_text(data = mtcarsProbs,
            aes(x = cyl, y = min-1,
                label = min))

mtcars boxplot with labels

编辑: 有没有办法让ggplot2自动计算并显示这些值?

r ggplot2 label
1个回答
0
投票

您可以首先创建一个没有文本的绘图,然后使用绘图自己的

layer_data

向其添加文本图层
library(tidyverse)

p <- ggplot(mtcars) +
  geom_boxplot(aes(group = cyl, x = gear, y = mpg)) 

p +
  geom_label(data = pivot_longer(layer_data(p), 1:5),
            aes(x = x, y = value, label = value))

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.