Home > front end >  Combine multiple plot in loop color each plot by different column in dataframe
Combine multiple plot in loop color each plot by different column in dataframe

Time:01-14

I am trying combine the multiple plots according to on of the enter image description here

CodePudding user response:

It looks like you are trying to create multiple scatter plots using the ggplot2 package in R, with each plot showing the relationship between Sepal.Length and Sepal.Width, and colored by one of the columns in the iris dataset (Petal.Length or Petal.Width). However, there are a few issues with your code.

First, in the line where you create the plots, you are using the variable i to set the color aesthetic, but i is a character string (i.e. the column name) rather than the actual data. You need to use the aes_string() function instead of aes() and pass in the column name as a string.

Second, in the for loop where you save the plots to the plot_list, you are using double square brackets [[i]] to index into the list, but you should use single square brackets [i] since you are indexing by the name of the column, not the value of the index.

Finally, you can use the cowplot package to arrange the multiple plots in one page.

Here's how you can fix the code:

library(ggplot2)
library(cowplot)

data(iris)
list_data=c("Petal.Length", "Petal.Width")

# Make plots.
plot_list = list()
for (i in list_data) {
   p = ggplot(iris, aes(y=Sepal.Length, x=Sepal.Width))  
   geom_point(size=3, aes_string(colour=i))
   plot_list[i] = p
}

pdf("plots.pdf")
plot_grid(plotlist=plot_list, ncol=2,   align="h")
dev.off()
  • Related