如何在对齐线/列上绘制对齐的文本?

时间:2019-06-06 09:13:28

标签: r ggplot2 r-grid cowplot

我正在通过具有对齐文本(左/右/上/下)的几行和几列创建一个“页面”。我想使用grid.arrange()函数,但是我做不到。我在一篇旧文章中读到grid_plot()函数可以完成这项工作。

所以我的代码是

# Libraries
library(ggplot2)
library(grid)
library(cowplot)

x <- unit(1:3/(3+1), "npc")
y <- unit(1:2/(2+1), "npc")
grid.grill(h=y, v=x, gp=gpar(col="grey"))

myPlot <- plot_grid(
  grid.text(label="Information:", x=x[1], y=y[2], just=c("left", "bottom"),  gp=gpar(fontface = "bold",  fontsize = 15, col = "black")),
  grid.text(label="Name:",        x=x[2], y=y[1], just=c("right", "bottom"), gp=gpar(fontface = "plain", fontsize = 13, col = "red")), 
  grid.text(label="John Doe ",    x=x[2], y=y[1], just=c("left", "bottom"),  gp=gpar(fontface = "plain", fontsize = 13, col = "blue"))
)

显示效果很好: Aligned plot

但是,如果我将图保存在pdf文件中,结果将是未对齐的

save_plot("myPlot.pdf", myPlot, nrow=3, ncol=2)

结果与预期不符 No aligned plot

我的问题是:如何对齐pdf文件中的文本?

1 个答案:

答案 0 :(得分:0)

在第一种情况下,您显示的结果是plot_grid的结果。发生的事情是grid.text函数(与textGrob不同)默认情况下会绘制创建的文本文件,因此三个文本文件中的每一个都在彼此的 top 中绘制。相同的Grid视口。从视口的角度来看,发生的情况等同于以下内容:

grid.grill(h=y, v=x, gp=gpar(col="grey"))
grid.text(label="Information:", x=x[1], y=y[2], just=c("left", "bottom"),  gp=gpar(fontface = "bold",  fontsize = 15, col = "black"))
grid.text(label="Name:",        x=x[2], y=y[1], just=c("right", "bottom"), gp=gpar(fontface = "plain", fontsize = 13, col = "red"))
grid.text(label="John Doe ",    x=x[2], y=y[1], just=c("left", "bottom"),  gp=gpar(fontface = "plain", fontsize = 13, col = "blue"))

同时,plot_grid函数将创建的文本杂点按照2行2列的排列方式进行排列,然后将结果分配给myPlot。在您的原始代码中,myPlot直到save_plot行才真正绘制出来。如果您在R / RStudio的图形设备中绘制了myPlot,它的外观将与pdf形式的外观相同。乍一看似乎未对齐的文本实际上完全按预期对齐了—一旦我们考虑到这些实际上是并排的图,而不是重叠的图:

myPlot
grid.grill(h = unit(1:5/6, "npc"), v = unit(1:7/8, "npc"), gp = gpar(col = "grey"))
grid.grill(h = unit(1/2, "npc"), v = unit(1/2, "npc"), gp = gpar(col = "black"))

enter image description here

如果您想将已经对齐的文本文件相互叠加,则根本不应该使用plot_grid。 Cowplot软件包中的低级功能可以更好地满足您的目的:

# this is a matter of personal preference, but I generally find it less confusing to
# keep grob creation separate from complex cases of grob drawing / arranging.
gt1 <- grid.text(label="Information:", x=x[1], y=y[2], just=c("left", "bottom"),  
                 gp=gpar(fontface = "bold", fontsize = 15, col = "black"))
gt2 <- grid.text(label="Name:",        x=x[2], y=y[1], just=c("right", "bottom"), 
                 gp=gpar(fontface = "plain", fontsize = 13, col = "red"))
gt3 <- grid.text(label="John Doe ",    x=x[2], y=y[1], just=c("left", "bottom"),  
                 gp=gpar(fontface = "plain", fontsize = 13, col = "blue"))

# ggdraw() & draw_plot() fill up the entire plot by default, so the results are overlaid.
myPlot <- ggdraw(gt1) + draw_plot(gt2) + draw_plot(gt3)
myPlot # show in default graphics device to check alignment
save_plot("myPlot.pdf", myPlot) # save as pdf

enter image description here