ggplot2:从宽高比中排除图例

时间:2013-01-31 17:21:15

标签: r ggplot2 knitr

我使用ggplot2knitr发布带有右侧图例的散点图。图例包含在宽高比中,因此打破了图的“方形度”,如default themes所示。当图例文本比“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 个答案:

答案 0 :(得分: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

相关问题