简体   繁体   中英

How to create a matrix of plots with R and ggplot2

I am trying to arrange n consecutive plots into one single matrix of plots. I get the plots in first place by running a for-loop, but I can't figure out how to arrange those into a 'plot of plots'. I have used par(mfrow=c(num.row,num.col)) but it does not work. Also multiplot(plotlist = p, cols = 4) and plot_grid(plotlist = p)

#import dataset
Survey<-read_excel('datasets/Survey_Key_and_Complete_Responses_excel.xlsx',
                      sheet = 2)

#Investigate how the dataset looks like
glimpse(Survey)#library dplyr

#change data types
Survey$brand <- as.factor(Survey$brand)
Survey$zipcode <- as.factor(Survey$zipcode)
Survey$elevel <- as.factor(Survey$elevel)
Survey$car <- as.numeric(Survey$car)

#Relation brand-variables
p = list()
for(i in 1:ncol(Survey)) {

    if ((names(Survey[i])) == "brand"){
      p[[i]]<-ggplot(Survey, aes(x = brand)) + geom_bar() +
        labs(x="Brand")

  } else if (is.numeric(Survey[[i]]) == "TRUE"){
     p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill=brand)) +     geom_histogram() +
      labs(x=colnames(Survey[i]))

   } else {
    p[[i]]<-ggplot(Survey, aes(x = Survey[[i]], fill = brand)) +     geom_bar() +
      labs(x=colnames(Survey[i]))
  }
}

I think plots are appended correctly to the list but I can not plot them in a matrix form.

The problem does not appear to be with your multiple plots, but how you are calling the variable into your plot.

You've already put "Survey" into ggplot as the first argument (the data slot). In the mapping argument (the second slot), you put in aes(...) and inside that you should be specifying variable names, not data itself. So try this:

Where you have aes(x = Survey[[i]], fill=brand)) in two places, put aes(x = names(Survey[[i]], fill=brand)) instead.

Regarding plotting multiple plots, par(mfrow... is for base R plots and cannot be used for ggplots. grid.arrange, multiplot, and plot_grid should all work once you fix the error in your plot.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM