Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

ggplot2 - R: arranging multiple plots together using gridExtra

I am using the R programming language. I am trying to arrange "plot1, plot2, plot3, plot4" on the same page:

library(kohonen) #fitting SOMs

library(ggplot2) #plots

library(GGally) #plots

library(RColorBrewer) #colors, using predefined palettes

 

iris_complete <-iris[complete.cases(iris),] #only complete cases... the iris dataset floats around in the sky with diamonds.

iris_unique <- unique(iris_complete) # Remove duplicates

 

#scale data

iris.sc = scale(iris_unique[, 1:4])

 

#build grid

iris.grid = somgrid(xdim = 10, ydim=10, topo="hexagonal", toroidal = TRUE)

 

# build model

set.seed(33) #for reproducability

iris.som <- som(iris.sc, grid=iris.grid, rlen=700, alpha=c(0.05,0.01), keep.data = TRUE)

 

 

###plots

 

var <- 1 #define the variable to plot

plot1 = plot(iris.som, type = "property", property = getCodes(iris.som)[,var], main=colnames(getCodes(iris.som))[var], palette.name=terrain.colors)

 

var <- 2 #define the variable to plot

plot2 = plot(iris.som, type = "property", property = getCodes(iris.som)[,var], main=colnames(getCodes(iris.som))[var], palette.name=terrain.colors)

 

var <- 3 #define the variable to plot

plot3 - plot(iris.som, type = "property", property = getCodes(iris.som)[,var], main=colnames(getCodes(iris.som))[var], palette.name=terrain.colors)

 

var <- 4 #define the variable to plot

plot4 = plot(iris.som, type = "property", property = getCodes(iris.som)[,var], main=colnames(getCodes(iris.som))[var], palette.name=terrain.colors)

 

 

 

 

g1 <- grid.arrange(plot1, nrow = 1)

g2 <- grid.arrange(plot2, nrow = 1)

g3 <- grid.arrange(plot3, nrow = 1)

g4 <- grid.arrange(plot4, nrow = 1)

 

grid.arrange(g1, g2, g3, g4, ncol = 1)

However, when I use the "grid.arrange()" function, I get an error : Error in gList - only 'grobs' allowed in gList"

Right now, I am considering running each of the "plot" statements individually, and manually joining them all using MS Paint. Is there a better way to do this?

Thanks

question from:https://stackoverflow.com/questions/65832784/r-arranging-multiple-plots-together-using-gridextra

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to keep the approach you are using just add

par(mfrow=c(2,2))

before all four plots.

If you want everything on the same line add instead

par(mfrow=c(1,4))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...