首页 > 解决方案 > ggplot2 从绘图旁边的附加数据框中添加数据

问题描述

我希望能够使用其他信息来扩展我的箱线图。这是 ggplot2 的一个工作示例:

library(ggplot2)

ToothGrowth$dose <- as.factor(ToothGrowth$dose)

# Basic box plot
p <- ggplot(ToothGrowth, aes(x=dose, y=len)) + 
  geom_boxplot()
# Rotate the box plot
p + coord_flip()

我想从单独的数据框中添加其他信息。例如:

extra <- data.frame(dose=factor(c(0.5,1,2)), label=c("Label1", "Label2", "Label3"), n=c("n=42","n=52","n=35"))

> extra
  dose  label    n
1  0.5 Label1 n=42
2    1 Label2 n=52
3    2 Label3 n=35

我想创建下图,其中每个剂量(因子)的信息在绘图之外并与每个剂量水平对齐(我在 powerpoint 中做了这个作为示例):

在此处输入图像描述

编辑:我想就初始问题的扩展征求意见。

我使用填充将两组剂量分开的这个扩展怎么样?

ToothGrowth$dose <- as.factor(ToothGrowth$dose)
ToothGrowth$group <- head(rep(1:2, 100), dim(ToothGrowth)[1])
ToothGrowth$group <- factor(ToothGrowth$group)

 p <- ggplot(ToothGrowth, aes(x=dose, y=len, fill=group)) + 
     geom_boxplot()
 # Rotate the box plot
 p + coord_flip()

extra <- data.frame(
  dose=factor(rep(c(0.5,1,2), each=2)), 
  group=factor(rep(c(1:2), 3)), 
  label=c("Label1A", "Label1B", "Label2A", "Label2B", "Label3A", "Label3B"), 
  n=c("n=12","n=30","n=20", "n=32","n=15","n=20")
)

是否可以将来自新数据框(额外,6 行)的数据与每个剂量/组组合对齐?

标签: rggplot2boxplot

解决方案


我们可以使用geom_textwith clip = "off"inside coord_flip

ggplot(ToothGrowth, aes(x=dose, y=len)) +
    geom_boxplot() +
    geom_text(
        y = max(ToothGrowth$len) * 1.1,
        data = extra,
        aes(x = dose, label = sprintf("%s\n%s", label, n)),
        hjust = 0) +
    coord_flip(clip = "off") +
    theme(plot.margin = unit(c(1, 5, 0.5, 0.5), "lines"))

在此处输入图像描述

说明:我们使用inside将文本放置在绘图区域之外geom_text并禁用剪切。最后,我们增加绘图边距以容纳额外的标签。您可以通过更改.clip = "off"coord_flipyy = max(ToothGrowth$len) * 1.1


作为对您的编辑的回应,这里有一种可能性

extra <- data.frame(
  dose=factor(rep(c(0.5,1,2), each=2)),
  group=factor(rep(c(1:2), 3)),
  label=c("Label1A", "Label1B", "Label2A", "Label2B", "Label3A", "Label3B"),
  n=c("n=12","n=30","n=20", "n=32","n=15","n=20")
)

library(tidyverse)
ToothGrowth %>%
    mutate(
        dose = as.factor(dose),
        group = as.factor(rep(1:2, nrow(ToothGrowth) / 2))) %>%
    ggplot(aes(x = dose, y = len, fill = group)) +
    geom_boxplot(position = position_dodge(width = 1)) +
    geom_text(
        data = extra %>%
            mutate(
                dose = as.factor(dose),
                group = as.factor(group),
                ymax = max(ToothGrowth$len) * 1.1),
        aes(x = dose, y = ymax, label = sprintf("%s\n%s", label, n)),
        position = position_dodge(width = 1),
        size = 3,
        hjust = 0) +
    coord_flip(clip = "off", ylim = c(0, max(ToothGrowth$len))) +
    theme(
        plot.margin = unit(c(1, 5, 0.5, 0.5), "lines"),
        legend.position = "bottom")

在此处输入图像描述

几点评论:

  1. position_dodge(with = 1)我们通过使用insidegeom_text和来确保标签与躲避的条相匹配geom_boxplot
  2. 似乎position_dodge不喜欢全局y(外部aes)。因此,我们将标签的 y 位置包含在其中extra并在其中使用它aes。因此,我们需要明确限制y轴的范围。我们可以在内部coord_flip使用ylim = c(0, max(ToothGrowth$len)).

推荐阅读