Knowledge base

use ggplot to passe in the drawing parameters in the form of variables


Sometimes we need to use a loop to draw multiple ggplot graphs, we fixed x, and y needs to loop multiple columns. At this time we can use aes_string, and its incoming parameters can be strings or variables, which can solve this problem well.

Code example

for (i in 2:3){
p <- ggplot(mtcars, aes_string(x = colnames(mtcars)[1], y= colnames(mtcars)[i])) +
  geom_point() + theme_bw()

Leave a Reply

Your email address will not be published. Required fields are marked *