ggplot2:将图例从宽高比中排除 [英] ggplot2: Exclude legend from aspect ratio

查看:68
本文介绍了ggplot2:将图例从宽高比中排除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ggplot2knitr发布带有右侧图例的散点图.图例包含在长宽比中,因此会破坏图的方形性",如中所示默认主题.当图例文本比"a"和"b"长一些时,图形将变成长矩形"而不是正方形".

I use ggplot2 and knitr to publish scatterplots with a right-hand-side legend. The legend is included in the aspect ratio and therefore breaks the "squareness" of the plots, as shown in the default themes. When the legend text becomes a bit longer than "a" and "b", the graphs become "long rectangles" instead of "squares".

我想使图形保持平方",因此要从我的ggplot2图形的宽高比中排除图例.我的.Rprofile具有以下信息,可以强制ggplot2生成颜色更大的文本和在轴标题周围留出更多空间的浅色图形:

I would like to keep the graphs "squared", and so would like to exclude the legend from the aspect ratio on my ggplot2 graphs. My .Rprofile has the following information to force ggplot2 to produce low-colour graphs with bigger text and more space around axis titles:

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选项的操作也失败了.感谢您的帮助!

Is there anything I can add here to exclude the legend from the aspect ratio? Manipulations with coord_equal and coord_fixed have failed so far, as have the fig.width and fig.height options. Thanks for your help!

编辑:已删除工作示例,并在下面以完整的示例代码回答了问题(对批准答案的延迟表示抱歉).

working example removed, question answered below with full example code (sorry for the delay in approving the answer).

推荐答案

设置coord_fixed()应该可以解决问题:

Setting coord_fixed() should do the trick:

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)

这篇关于ggplot2:将图例从宽高比中排除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆