将绘图旋转 90 度以获得边缘分布

Rotate plot 90deg for marginal distribution

我正在尝试在基础 R 中获取边际分布图 (如果不可能,非基础 R 代码也可以,但仅用于旋转)。

如何旋转y轴边缘图(黄色)?

我必须制作这个情节的代码:

# plot layout
layout_mat <- matrix(c(2, 0,
                       1, 3),
                     nrow = 2,
                     byrow = T)

layout(layout_mat, c(3, 1), c(1, 3))

par(mar = c(3,3,1,1))

# main scatterplot
plot(x = mtcars[order(mtcars$qsec), c("wt", "mpg")],
     xlab = "Vehicle Weight (1000 lbs)",
     ylab = "Miles Per Gallon (MPG)",
     pch = 16,
     cex = seq(3.5, 1.25, length.out = nrow(mtcars)),
     col = rgb(0, 0, 0, .5),
     axes = F,
     xlim = c(1, 6),
     ylim = c(8, 35))
box(lwd = 1.5)
axis(side = 1, at = 1:6, labels = 1:6, lwd = 0, lwd.ticks = 1)
axis(side = 2, at = seq(10, 35, 5), label = seq(10, 35, 5), lwd = 0, lwd.ticks = 1, las = 1)

dx <- density(mtcars[order(mtcars$qsec), "wt"])
dy <- density(mtcars[order(mtcars$qsec), "mpg"])

# x axis plot
par(mar = c(0,3,1,1))
plot(dx, axes = F, main = "", xlab= "", ylab = "", lwd =2)

# y-axis plot
par(mar = c(3,0,1,1))
plot(dy, axes = F, main = "", xlab= "", ylab = "", lwd =2)
rect(xleft = par("usr")[1],
     ybottom = par("usr")[3],
     xright = par("usr")[2],
     ytop = par("usr")[4],
     col = rgb(235, 216, 52, .5*255, maxColorValue = 255))

感谢@user20650 的回答

将 y 密度的 y 轴点传递给 x 并将 y 密度的 x 轴点传递给 y 将翻转绘制:

plot(dy$y, dy$x, type="l", axes = F, main = "", xlab= "", ylab = "", lwd = 2)