r - 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 行)的数据与每个剂量/组组合对齐?
解决方案
我们可以使用geom_text
with 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_flip
y
y = 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")
几点评论:
position_dodge(with = 1)
我们通过使用insidegeom_text
和来确保标签与躲避的条相匹配geom_boxplot
。- 似乎
position_dodge
不喜欢全局y
(外部aes
)。因此,我们将标签的 y 位置包含在其中extra
并在其中使用它aes
。因此,我们需要明确限制y
轴的范围。我们可以在内部coord_flip
使用ylim = c(0, max(ToothGrowth$len))
.
推荐阅读
- ionic-framework - 如何在离子列表上放置正确的子图块
- javascript - 使用 Pyppeteer 获取阴影根中的元素内容
- sql-server - 如何将逗号拆分数据与 1 个字段分开并移至 SSMS 中的 2 个单独字段?
- c# - 允许对 asp.net core 2.x 中的静态文件进行 POST 访问
- javascript - 使用 jest 编写流式测试
- python - dask 在运行函数之前是否等待资源可用?
- bash - 将时间戳附加到从 AWK 脚本生成的日志条目
- java - Netbeans 中的 FXML 文件不断将更改还原为原始副本?
- makefile - 删除源文件时增量制作失败
- html - 如何将这两个图像对齐在同一行?