R在网格排列中间添加单词

nzrxty8p  于 2022-12-06  发布在  其他
关注(0)|答案(2)|浏览(156)

我正在写R ggplot,我正在用grid.arrange安排多个情节。
有没有办法在两个情节之间添加一些单词?我希望输出像红色的单词一样。
谢谢你的帮助:)

library(ggplot2)
library(gridExtra)
P1 <- ggplot(mtcars, aes(x = mpg)) +
  geom_histogram()
P2 <- ggplot(mtcars, aes(x = wt)) +
  geom_histogram()
grid.arrange(P1, *I want to add some information here*,P2, ncol = 1, nrow = 2)

tgabmvqs

tgabmvqs1#

您可以使用grid库中的grid.text函数,如下所示

### Libraries
library(grid)
library(ggplot2)
library(gridExtra)

### Data
data(cars)

### Initiating plots
P1 <- ggplot(mtcars, aes(x = mpg)) +
  geom_histogram()

P2 <- ggplot(mtcars, aes(x = wt)) +
  geom_histogram()

### Display plots
grid.arrange(P1, P2, ncol = 1, nrow = 2)+
grid.text("I want to add some information here", 
          x=unit(0.25, "npc"), 
          y=unit(.52, "npc"),
          gp=gpar(fontsize=20, col="red"))

rhfm7lfc

rhfm7lfc2#

一种方法是创建另一个只包含所需文本的ggplot,并在cowplot::plot_grid中使用它

library(ggplot2)

P1 <- ggplot(mtcars, aes(x = mpg)) + geom_histogram()

P2 <- ggplot() + 
  annotate("text", x = 4, y = 25, size=8, 
           label = "This is some text in the middle", color = "red") + 
  theme_void() 

P3 <- ggplot(mtcars, aes(x = wt)) +  geom_histogram()

cowplot::plot_grid(P1, P2, P3, rel_heights = c(1/2, 1/12, 1/2), 
                   align = "v", nrow = 3)

相关问题