如何:当 x 轴和 y 轴处于不同比例时自动设置固定坐标比 (coord_fixed)?

JBJ*_*JBJ 6 plot r aspect-ratio ggplot2

我的目标是通过 .ggplot2 修复绘图的坐标纵横比coord_fixed()。我认为coord_fixed(ratio=1)独立于 x 轴或 y 轴的比例完成了这项工作。我的直觉:参数ratio是指坐标x的总范围总范围的比值坐标y的。暗示比率为 1 总是意味着 x 轴将与图中的 y 轴一样长。

然而,对于 1000 秒的 x 坐标和 y 坐标(例如百分比),coord_fixed 的行为并不像我预期的那样。

2 问题:

  1. 你能解释一下为什么 coord_fixed 考虑了数据的实际比例而不是整个坐标长度吗?
  2. 我可以以编程方式更改 coord_fixed 以始终引用 x 和 y 坐标值的整个范围吗?

这是一个插图

library("ggplot2")
set.seed(123)
df = data.frame(x=runif(11)*1000,y=seq(0,.5,.05))
ggplot(df, aes(x,y)) +geom_point() +coord_fixed(1)
Run Code Online (Sandbox Code Playgroud)

产生 在此处输入图片说明

通过 coord-fixed 中 x 和 y 值的比率重新缩放数据解决了这个问题

ggplot(df, aes(x,y)) +geom_point() +coord_fixed(1*max(df$x)/max(df$y))
Run Code Online (Sandbox Code Playgroud)

然而,这不是程序性的。我必须df$x手动指定才能达到预期的效果。请参阅问题 2:是否有一种明智的方法可以coord_fixed根据我的 ggplot 图中 x/y 轴上的数据自动重新缩放坐标?

在此处输入图片说明

Gre*_*gor 7

你能明白为什么要coord_fixed考虑数据的实际比例而不是整体的坐标长度吗?

这就是coord_fixed. 例如,当xy是相同单位的长度度量时,它特别有用。(基本上,只要xy具有相同的单位,coord_fixedratio = 1是你想要的。)

例如,如果我的数据是一个正方形和一个三角形,coord_fixed则是使正方形实际上是正方形的唯一方法

shapes <- data.frame(x = c(1, 1, 2, 2, 1, 3, 3, 4, 3),
                     y = c(1, 2, 2, 1, 1, 1, 2, 1, 1),
                     name = c(rep("square", 5), rep("isosceles triangle", 4)))

shape.plot <- ggplot(shapes, aes(x = x, y = y, group = name, color = name)) +
    geom_path()

shape.plot # distorted
shape.plot + coord_fixed() # square!
Run Code Online (Sandbox Code Playgroud)

我可以以编程方式更改 coord_fixed 以始终引用 x 和 y 坐标值的整个范围吗?

我建议不要覆盖它,您可以尝试创建自己的版本,就像在您的答案中一样(尽管如果您想从xy规范中提取适当的值,aes()您将面临挑战---并且您将学习更多关于 ggplot 的内部工作的信息比我知道的要多)。但是,默认行为(未指定 any coord)似乎正是您要寻找的。

如果你比较

# your code
ggplot(df, aes(x,y)) + geom_point() + coord_fixed(1 * max(df$x) / max(df$y))

# no coord at all
ggplot(df, aes(x,y)) + geom_point()
Run Code Online (Sandbox Code Playgroud)

他们基本上是一样的。所以,coord_fixed你似乎正在寻找的修改是不要使用 coord_fixed.

绘图区域的纵横比(与坐标无关):不要使用 coord_fixed

刚刚从这个半相关的帖子中发现了这一点:如果您想要绘图区域的特定纵横比,您可以使用theme(),例如

p1 <- ggplot(df, aes(x,y)) + geom_point()
p1 + theme(aspect.ratio = 1)
p1 + theme(aspect.ratio = (1 + sqrt(5))/ 2)  # golden ratio portrait
p1 + theme(aspect.ratio = 2 / (1 + sqrt(5))) # golden ratio landscape
Run Code Online (Sandbox Code Playgroud)

当然,这与数据无关。我认为要带回家的信息是,如果您希望将数据的比例考虑在内,相对于彼此,请使用coord_fixed. 如果要更改绘图区域的纵横比但仍适合数据,请使用theme(aspect.ratio). 如果要更改已保存文件的纵横比,请使用保存函数的高度和宽度参数。