ggplot2:aspect.ratio 压倒 coord_equal 或 coord.fixed

ggplot2: aspect.ratio overpowers coord_equal or coord.fixed

无论我的数据点云的形状如何,我都想收到一个坐标相等的方形图。

这是我的问题的原始说明。

xy <- data.frame(x = rnorm(100),
                 y = rnorm(100, mean = 1, sd = 2))
gg <- ggplot(xy,aes(x = x, y = y))+
        geom_point()
gg + coord_equal() #now we have square coordinate grid
gg + theme(aspect.ratio = 1) #now the plot is square

# if we use both, aspect.ratio overpowers coord_equal
gg + coord_equal() + theme(aspect.ratio = 1)  

有什么方法可以同时对绘图和坐标网格进行平方吗?当然,情节中会有一些空白区域。我不介意这个。

另外,我想知道确保 x 轴和 y 轴上的标记相等的最简单方法。

最简单的方法是分别指定 x-lim 和 y-lim:

gg + coord_equal() +xlim(c(-6,6)) + ylim(c(-6,6))

您可以轻松地用基于数据 (?extendrange) 派生 min/and 的函数替换它。

您可以通过手动设置轴的比例来强制绘图为正方形:

gg +
scale_x_continuous(limits=c(min(xy$x,xy$y), max(xy$x,xy$y))) +
scale_y_continuous(limits=c(min(xy$x,xy$y), max(xy$x,xy$y))) +
theme(aspect.ratio=1)

您实际上并不需要 theme() 部分,因为您可以在 coord_fixed() 内完成此操作。 对于您的示例,您可以执行以下操作:

gg <- ggplot(xy,aes(x = x, y = y))+
        geom_point()
gg + coord_fixed(ratio=1,xlim=c(floor(min(xy$x,xy$y)),
                 ceiling(max(xy$x,xy$y))),
                 ylim=c(floor(min(xy$x,xy$y)), ceiling(max(xy$x,xy$y))))

通过在 x 和 y 轴中使用 ceilingfloor,您不会遇到轴限制位于外部点之上的问题。