繁体   English   中英

在不更改轴比例的情况下控制ggplot2图例位置

[英]Control ggplot2 legend position without changing the scale of the axes

之所以想到这个问题,是因为我想对地块进行幻灯片显示,以显示我要制作的结构。 这些图都是正方形的,我想保持这种方式(轴应具有相等的比例)。

我可以很容易地做到这一点,例如:

library(ggplot2)
library(magrittr)

dd <- data.frame(x = runif(100), y = runif(100), z = rexp(100))
dd %>% ggplot(aes(x = x, y = y)) 
dd %>% ggplot(aes(x = x, y = y)) + geom_point() 

您会注意到这两个图如何很好地“对齐”,在某种意义上,如果我以相同的大小导出它们,可以看到以幻灯片显示的方式添加了点。

但是,当出现图例时,轴会变形以适合相同大小的图例:

dd %>% ggplot(aes(x = x, y = y)) + geom_point(aes(size = z))

有没有一种方法可以使这三个图按顺序很好地对齐,以使轴在所有三个图中都保持在同一位置?

这将绘制三个图,以便图面板保持相同的形状和大小。 我使用gtable函数。 前两个地块没有图例。 因此,我在其gtable中添加了一个列,以使前两个的布局与第三个的布局相同。 然后,确保前两个图的列宽与第三个图的宽度相同。

此外,如果您希望轴具有相等的比例,请考虑将coord_fixed(ratio = 1)到每个图。

library(ggplot2)
library(magrittr)
library(gtable)
library(grid)

dd <- data.frame(x = runif(100), y = runif(100), z = rexp(100))

# Get the  ggplots
p1 = dd %>% ggplot(aes(x = x, y = y)) 
p2 = dd %>% ggplot(aes(x = x, y = y)) + geom_point() 
p3 = dd %>% ggplot(aes(x = x, y = y)) + geom_point(aes(size = z))

# Get the ggplot grobs
g1 = ggplotGrob(p1)
g2 = ggplotGrob(p2)
g3 = ggplotGrob(p3)

# Add a column to g1 and g2 (any width will do)
g1 = gtable_add_cols(g1, unit(1, "mm"))
g2 = gtable_add_cols(g2, unit(1, "mm"))

# Set g1 and g2 widths to be equal to g3 widths
g1$widths = g3$widths
g2$widths = g3$widths

# Draw them
grid.newpage()
grid.draw(g1)
grid.draw(g2)
grid.draw(g3)

我没有得到100%准确的解决方案。 但是我认为这非常接近。 我不知道如何确定图例标签的宽度。 如果您知道该怎么做,则可以相应地调整边距。 对于此解决方案,我使用图例和绘图边距进行处理。

library(dplyr)
library(ggplot2)

dd <- data.frame(x = runif(100), y = runif(100), z = rexp(100))
dd %>% ggplot(aes(x = x, y = y)) + 
  theme(plot.margin = unit(c(1,3.72,1,1), "cm"))


dd %>% ggplot(aes(x = x, y = y)) + geom_point() + 
  theme(plot.margin = unit(c(1,3.72,1,1), "cm")) 

dd %>% ggplot(aes(x = x, y = y)) + geom_point(aes(size = z)) + 
  theme(plot.margin = unit(c(1,1,1,1), "cm"),
        legend.margin = unit(0.5, "cm"),
        legend.text = element_text(size = 12))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM