【问题标题】:R - How do I line up axes between a boxplot and matplot?R - 如何在箱线图和 matplot 之间排列轴?
【发布时间】:2020-12-01 00:41:27
【问题描述】:

我在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】:

    user20650 的评论解决了我的问题,因此我将冒昧地将其扩展为更大的答案并链接到我在该问题上找到的一些文档。根据lecture notes的一些基础图形参数,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 = '');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-23
      • 2021-10-09
      • 2021-01-04
      • 2011-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多