r中箱形图中的附加轴

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

我有以下数据:

df1 <- read.table(text = "ID Group Value time
A1 A 21 10
A2 A 79 20
A3 A 32 30
B1 B 105 40
B2 B 44 50
B3 B 58 60
C1 C 32 70
C2 C 66 80
C3 C 143 90", stringsAsFactors = FALSE, header = TRUE)

根据数据,我使用ggboxplot函数绘制一个箱形图:

library(ggpubr)

ggboxplot(data=df1,x="Group",y="Value",add = "jitter",short.panel.labs = FALSE)

我的情节就像:enter image description here

现在我想在图的顶部添加一个额外的轴,根据time中的df1列将图中的“点”重新排列,我应该做的是:

enter image description here

那可能吗?

r ggplot2 plot boxplot ggpubr
1个回答
1
投票

如果你不依赖ggboxplot(),那就有一个基本情节的解决方案。

boxplot(Value ~ Group, df1, xlim=c(.4, 3.5),
        xlab="Group", ylab="Value")
points(df1$time/100*3.5, df1$Value, pch=16)
axis(3, seq(0, 3.5, length.out=11), 0:10*10)
mtext("time", 3, 3)

说明

我们首先制作一个正常的箱形图,然后用xlim()向左略微扩展y轴(否则从0.5开始)。然后我们通过将次要x轴(points())缩放到箱线图的x轴的[0,3.5]范围来用"time"覆盖该图。然后我们添加轴并标记它,最后我们使用mtext()为辅助x轴添加标签。

结果

enter image description here

数据

df1 <- structure(list(ID = c("A1", "A2", "A3", "B1", "B2", "B3", "C1", 
"C2", "C3"), Group = c("A", "A", "A", "B", "B", "B", "C", "C", 
"C"), Value = c(21L, 79L, 32L, 105L, 44L, 58L, 32L, 66L, 143L
), time = c(10L, 20L, 30L, 40L, 50L, 60L, 70L, 80L, 90L)), class = "data.frame", row.names = c(NA, 
-9L))
© www.soinside.com 2019 - 2024. All rights reserved.