R - 如何在箱线图和 matplot 之间排列轴?

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

我在

R
中创建了一个并排图,其中两个图都应该使用相同的 y 轴。但是,左侧的图是
boxplot
,右侧的图是
matplot
,并且在这两个图中我都设置了相同的 y 轴范围
ylim = c(0, YMAX)
。不幸的是,正如您在下面看到的,这些图似乎没有使用相同的布局范围——条形图将范围直接延伸到轴的边缘,而 matplot 在轴的每个边缘都有一个缓冲区。因此,图上的 y 轴未按预期排列。

#Create layout for plot
LAYOUT <- matrix(c(rep(1, 2), 2:3), nrow = 2, ncol = 2, byrow = TRUE)
layout(LAYOUT, heights = c(0.1, 1))

#Create plot matrix
par(mar = c(0.5, 2.1, 0.5, 2.1), mgp = c(3, 1, 0), las = 0)
plot.new()
text(0.5,0.5, 'Barplot and Violin Plot', cex = 1.2, font = 2)
par(mar = c(5.1, 4.1, 2.1, 2.1), mgp = c(3, 1, 0), las = 0)

#Generate data for plot
x <- 1:100
y <- rchisq(100, df = 40)

#Generate plots
DENS <- density(y)
YMAX <- 1.4*max(y)
barplot(y, names.arg = x, ylim = c(0, YMAX))
matplot(x = cbind(-DENS$y, DENS$y), y = DENS$x,
        type = c('l', 'l'), lty = c(1, 1),
        col = c('black', 'black'),
        xlim = c(-max(DENS$y), max(DENS$y)), 
        ylim = c(0, YMAX), 
        xlab = 'Density', ylab = '')

如何调整此图以对齐 y 轴? (理想情况下,我希望右侧的图将刻度线放在轴的边缘,就像左侧的情况一样。)

r plot axis
1个回答
3
投票

user20650的评论解决了我的问题,因此我将冒昧地将其扩展为更大的答案,并链接到我在该问题上找到的一些文档。根据一些关于基础图形参数的讲义R

中的一些基础图默认添加超出指定轴范围的6%缓冲区。命令 
xasx = 'i'
yasx = 'i'
 
inhibit 此缓冲区(分别在 x 轴和 y 轴上),以便轴限制向右到轴的边缘。

将此解决方案应用于当前问题中的 y 轴(我们不将其应用于 x 轴,因为我们希望保留该轴上的缓冲区)给出以下命令和绘图。从图中可以看出,两个图中的 y 轴现在正确对齐。万岁!

#Create layout for plot LAYOUT <- matrix(c(rep(1, 2), 2:3), nrow = 2, ncol = 2, byrow = TRUE) layout(LAYOUT, heights = c(0.1, 1)) #Create plot matrix par(mar = c(0.5, 2.1, 0.5, 2.1), mgp = c(3, 1, 0), las = 0) plot.new() text(0.5,0.5, 'Barplot and Violin Plot', cex = 1.2, font = 2) par(mar = c(5.1, 4.1, 2.1, 2.1), mgp = c(3, 1, 0), las = 0) #Generate data for plot x <- 1:100 y <- rchisq(100, df = 40) #Generate plots DENS <- density(y) YMAX <- 1.4*max(y) barplot(y, names.arg = x, ylim = c(0, YMAX)) matplot(x = cbind(-DENS$y, DENS$y), y = DENS$x, yaxs = 'i', type = c('l', 'l'), lty = c(1, 1), col = c('black', 'black'), xlim = c(-max(DENS$y), max(DENS$y)), ylim = c(0, YMAX), xlab = 'Density', ylab = '')

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