I have this list of dataframes
i want to generate the same plot for each of dataframe. (the columns of interest share the same name, that are : " COType ; Zscore ; SpatialLag ".
Here's my code plotting a single dataframe (Community) :
ggplot(List_df_EU[["COMMUNITY"]], aes(x = Zscore,
y = SpatialLag,
fill = COType))
geom_point(color = "white", shape = 21, size = 2)
theme_minimal()
geom_hline(yintercept = 0, linetype = "dashed", size = 0.7)
geom_vline(xintercept = 0, linetype = "dashed", size = 0.7)
scale_fill_manual(values = color_values)
labs(title = names(List_df_EU[1]),
subtitle = "Graph de Moran sur les scores ESG des entreprises EU",
x = "z-score",
y = "Spatial lag",
fill = "Type de voisinage")
theme_fivethirtyeight()
theme (axis.title = element_text(), text = element_text(family = myFont1))
Here's the code supposed to create a single plot for each dataframe. it doesn't fill the list and doesn't send error message back
plotlist <- vector()
plotlist <- for(i in 1:length(List_df_EU)) {
ggplot(List_df_EU[[i]], aes(x = Zscore,
y = SpatialLag,
fill = COType))
geom_point(color = "white", shape = 21, size = 2)
theme_minimal()
geom_hline(yintercept = 0, linetype = "dashed", size = 0.7)
geom_vline(xintercept = 0, linetype = "dashed", size = 0.7)
scale_fill_manual(values = color_values)
labs(title = names(List_df_EU[[i]]),
subtitle = "Graph de Moran sur les scores ESG des entreprises EU",
x = "z-score",
y = "Spatial lag",
fill = "Type de voisinage")
theme_fivethirtyeight()
theme (axis.title = element_text(), text = element_text(family = myFont1))
}
If you have any tips it would be awesome!(Would be deseperate move generating plots manually)
CodePudding user response:
To run the same ggplot
code over a list of dataframes, I think lapply
is better than a for loop. Try this:
plotlist <- lapply(names(List_df_EU), function(x) {
ggplot(List_df_EU[[x]], aes(x = Zscore,
y = SpatialLag,
fill = COType))
geom_point(color = "white", shape = 21, size = 2)
theme_minimal()
geom_hline(yintercept = 0, linetype = "dashed", size = 0.7)
geom_vline(xintercept = 0, linetype = "dashed", size = 0.7)
scale_fill_manual(values = color_values)
labs(title = x,
subtitle = "Graph de Moran sur les scores ESG des entreprises EU",
x = "z-score",
y = "Spatial lag",
fill = "Type de voisinage")
theme_fivethirtyeight()
theme (axis.title = element_text(), text = element_text(family = myFont1))
}
CodePudding user response:
the issue is that you're assigning the new plot to plotlist at every iteration of the loop and the previous iteration is being overwritten.
You'd need to assign the new iteration to a new index of the list. e.g.
for (i in listOfPlotsToMake)
{
plotlist[[i]] <- listOfPlotsToMake[i]...
}