如何在使用ggplot2隐藏刻度时保持图形大小?

3

我正在使用ggplot2绘制散点图。当我隐藏刻度时,图形会自动变得稍微大一些。例如:

ggplot(data = iris, geom = 'blank', aes(y = Petal.Width, x = Petal.Length)) + geom_point()

ggplot(data = iris, geom = 'blank', aes(y = Petal.Width, x = Petal.Length)) +
geom_point() +
theme(axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      legend.position = "none")

第二个图形更大。我该如何避免它?我只想隐藏刻度和标签,但保留第一个图形的绘图,因为我想将两个图形组合在一起,一个有刻度,一个没有,但保持绘图大小相同。谢谢。
1个回答

4
棘手但可行。白色轴。
ggplot(data = iris, geom = 'blank', aes(y = Petal.Width, x = Petal.Length)) + geom_point()

+ theme (axis.title.x = element_text(family = "sans", face = "bold"))
ggplot(data = iris, geom = 'blank', aes(y = Petal.Width, x = Petal.Length)) +
  geom_point() +
  theme(axis.title.x = element_text(family = "sans", face = "bold",colour='white'))+
  theme(axis.title.y = element_text(family = "sans", face = "bold",colour='white'))

编辑: 通用解决方案

p1 <- ggplot(data = iris, geom = 'blank', aes(y = Petal.Width, x = Petal.Length)) + geom_point()

p2 <- ggplot(data = iris, geom = 'blank', aes(y = Petal.Width, x = Petal.Length)) +
  geom_point() +
  theme(axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        legend.position = "none")

gA <- ggplot_gtable(ggplot_build(p1))
gB <- ggplot_gtable(ggplot_build(p2))
gA$widths  <- gB$widths
gA$heights <- gB$heights

plot(gA)
plot(gB)

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