ggplot2: Exclude legend from aspect ratio

独自空忆成欢 提交于 2021-02-07 19:18:38

问题


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".

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")
)

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!

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


回答1:


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)

enter image description here



来源:https://stackoverflow.com/questions/14631523/ggplot2-exclude-legend-from-aspect-ratio

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!