如何在 R 中创建双轴箱线图?

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

我想创建一个包含两个 y 轴(均以不同比例连续)和一个因子作为 x 轴的箱线图。理想情况下,因子的每个水平都应该有一个包含每个连续变量的框。我需要一个像this one这样的箱线图,如这个问题的第一个答案中所述。但在 R.

到目前为止,我调整了此示例中的代码以包含箱线图和点图。但是,我无法使第二个变量的图出现在前一个变量的旁边而不是下面。

data <- data.frame(Factor1=factor(c("A", "B","A", "B","A", "B","A", "B", "A", "B","A",     "B","A", "B","A", "B", "A", "B","A", "B", "A", "B", "A", "B","A", "B", "A", "B","A", "B","A",     "B","A", "B", "A", "B")), Cont1=rnorm(36, mean=100, sd= 15), Cont2=rnorm(36, mean=0.35, sd=0.05))

par(mar=c(5, 4, 4, 6) + 0.5)

## Plot first continuous variable
# Boxplot
boxplot(Cont1 ~ Factor1, data = data, col="white", boxcol=2, xlim=c(0.5, 3.5 + length(unique(data$Factor1))),axes=FALSE, xlab="", ylab="")

# Points
stripchart(Cont1 ~ Factor1, data = data,method = "jitter",pch = 19,col = 2,vertical = TRUE,add = TRUE)

mtext("Cont1", side=2, line=2.5, col=2)
box()
axis(2, col=2, col.axis=2,las=1)  ## las=1 makes horizontal labels


## Allow a second plot on the same graph
par(new=TRUE)

## Plot the second continuous variable
# Boxplot
boxplot(Cont2 ~ Factor1, data = data, col="white", boxcol=3,xlim=c(0.5, 5.5), axes=FALSE, xlab="", ylab="") # with these limits the new boxplot and dotplot shows up below the previous ones, rather than next to them

# Points
stripchart(Cont2 ~ Factor1, data = data,method = "jitter", pch = 19, col = 3, vertical = TRUE, add = TRUE)
## a little farther out (line=4) to make room for labels
mtext("Cont2", side=4,col=3,line=4) 
axis(4, col=3,col.axis=3,las=1)

## Draw the factor axis
mtext("Factor1", side=1, col="black", line=2.5)  

I would be happy hearing about how to improve this code, but also with new suggestions.

Thanks!
r boxplot
1个回答
0
投票

因此,鉴于您想使用基本 R,我建议如下:

转换应在第二个 y 轴上表示的数据,使其位于第一个轴的大致范围内,并记住该标量。因此,如果使用基础 R,我们需要进行相同的转换。所以有更好的方法,但是......

data <- data.frame(
  Factor1 = factor(rep(c("A", "B"), times = 18)),
  Cont1 = rnorm(36, mean=100, sd= 15),
  Cont2 = rnorm(36, mean=0.35, sd=0.05)
)

vec1 <- data$Cont1[data$Factor1 == "A"]
vec2 <- data$Cont1[data$Factor1 == "B"]
vec3 <- data$Cont2[data$Factor1 == "A"] * 300
vec4 <- data$Cont2[data$Factor1 == "B"] * 300

datn <- as.data.frame(cbind(vec1, vec2, vec3, vec4))
head(datn)

绘制没有轴的分组箱线图。

par(mar=c(5, 4, 4, 6) + 0.5)

boxplot(
  x = datn,
  axes = FALSE,
  ylim = c(0, 250),
  col = rep(c("lightcyan", "salmon"), times = 2),
  border = "gray25"
)

手动添加轴。添加第二个轴(边 = 4)时变换标签,以便它们以原始比例显示数据。

axis(
  side = 1,
  at = c(1.5, 3.5),
  labels = c("Cont1", "Cont2")
)

axis(
  side = 2,
  at = seq(0, 300, 100),
  labels = seq(0, 300, 100),
  las = 2
)

axis(
  side = 4,
  at = seq(0, 300, 100),
  labels = round(seq(0, 300, 100) / 300, digits = 2),
  las = 2
)

box(which = "plot")

最后添加条形图的点。

stripchart(
  x = datn,
  method = "jitter",
  pch = 19,
  col = "lightgreen",
  vertical = TRUE,
  add = TRUE
)

这应该给出(未格式化):

编辑后的代码应生成下图(部分格式化):

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