Home > front end >  Create multiple plots from multiple dataframes (not ggplot) in r
Create multiple plots from multiple dataframes (not ggplot) in r

Time:10-23

Hello, I have a large dataframe which I split following the next code:

DF2 <- split(df, df$Species)
        new_names <- as.character(unique(df$Species))
    for (i in 1:length(DF2)) {
      assign(new_names[i], DF2[[i]])
    }

Giving me many dataframes with each having the same starting letters DF2Fish-XX with the XX being the unique species:

Now I want to have a loop function to create multiple plots using the following code to for each Species (unique dataframe):

par(mfrow=c(2,2))
DF2Plot <- function(index){plot(DF2Fish-XX[,index] ~ DF2Fish-XX$Year, 
                          main=names(DF2Fish-XX[index]), xlab= "Years", 
                          ylab = "Trophic position", type="b", xlim=range(1930:2020), ylim=range(2:5))}
lapply(2:5, FUN= DF2Plot)

Is there a way to have the second part of the script (creating the plot) in a loop for each unique species/dataframe created in the first part of code?

Any help is welcome.

Thanks in advance!

CodePudding user response:

I'll demonstrate using iris.

irisL <- split(iris, iris$Species)
names(irisL)
# [1] "setosa"     "versicolor" "virginica" 
par(mfrow = c(2, 2))
for (nm in names(irisL)) {
  plot(Sepal.Length ~ Sepal.Width, data=irisL[[nm]], main=nm)
}

iris separated plots

If your list of frames is not named, then you can index this way:

for (ind in seq_along(irisL)) {
  # ...
}

though you will need a direct way to infer the name (perhaps as.character(irisL[[ind]]$Species[1])).

  • Related