ggplot2:从纵横比中排除图例

4
我使用ggplot2knitr发布带有右侧图例的散点图。图例包含在纵横比中,因此破坏了图形的“正方形度”,如默认主题所示。当图例文本变得比“a”和“b”稍长时,图形会变成“长方形”而不是“正方形”。
我想保持图形的“正方形度”,因此希望在我的ggplot2图形中将图例从纵横比中排除。我的.Rprofile文件包含以下信息,以强制ggplot2生成低色彩的图形,并具有更大的文本和轴标题周围的空间:
theme_set(theme_bw(16))
theme_update(
  axis.title.y = element_text(angle = 90, vjust = -.25),
  axis.title.x = element_text(vjust = -1),
  plot.margin = unit(c(1,1,1,1), "cm")
)

有什么方法可以排除图例对纵横比的影响吗?使用 coord_equalcoord_fixed 进行操作以及使用 fig.widthfig.height 选项均未成功。感谢您的帮助!编辑: 工作示例已删除,下面是带有完整示例代码的答案(抱歉批准答案的延迟)。

1
这是它的链接:http://rpubs.com/briatte/3978 - Fr.
1个回答

5

使用 coord_fixed() 函数可以解决问题:

library(ggplot2)
library(gridExtra)  ## for grid.arrange()

## Create some data with one longer label
cars <- transform(mtcars, 
           cyl = factor(cyl, labels=c("4","6","8 is big")))


## Compute ratio needed to make the figure square
## (For a taller narrow plot, multiply ratio by number > 1; 
##  for a squatter plot, multiply it by number in the interval (0,1))    
ratio <- with(cars, diff(range(mpg))/diff(range(wt)))

## Make plots with and without a legend
a <- ggplot(cars, aes(mpg, wt)) + 
     geom_point() + coord_fixed(ratio=ratio)

b <- ggplot(cars, aes(mpg, wt, color=cyl)) + 
     geom_point() + coord_fixed(ratio=ratio)

## Plot them to confirm that coord_fixed does fix the aspect ratio
grid.arrange(a,b, ncol=2)

enter image description here


这在我的端上没有产生任何结果(请参见示例结尾):http://rpubs.com/briatte/3978 -- 无论是在 knitr 输出还是在 RStudio 绘图窗口中都没有。可能只是因为我不太理解在该工作流程中如何生成图形的纵横比。 - Fr.
刚才我添加的示例怎么样?如果这也不行,那么可能是您的设置有问题。 - Josh O'Brien
我一定表达得非常不清楚,因为我试图修复的问题在您的绘图中也出现了。在您的右侧示例中,我正在尝试保持灰色画布正方形。我在这里勾画了表面:http://i.imgur.com/s7SVuz6.png -- 如果纵横比为1:1,则表面将是正方形而不是矩形。相反,整个绘图是正方形。如何使图例不参与计算纵横比? - Fr.
@Fr. -- 我终于明白你的意思了,并相应地编辑了我的答案。 - Josh O'Brien
非常感谢,我想这就是我要找的。我仍然对ggplot2中文本最终变得如此小不满意,但这是关于ggplot2输出的更一般的问题。再次感谢。 - Fr.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接