I am writing R ggplot, and I am arranging multiple plots with grid.arrange
.
Is there a way to add some words in in between two plots? I want the output to be like the red word.
Thank you for your help :)
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)
CodePudding user response:
You could use the grid.text
function from grid
library as follows
### 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"))
CodePudding user response:
One approach would be to create another ggplot
with only text that you want and use it in 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)