3dok
3dok

Reputation: 103

Multiple plots with grid.arrange

My data set is a data.frame NewAuto, which has names:

[1] "mpg"          "cylinders"    "displacement" "horsepower"   "weight"      
[6] "acceleration" "year"         "origin"       "name"         "MPG01"

I want to make seven plots on one picture with ggplot. It's a part of bigger code. My aim is to make similar plots mpg vs other columns. Each plot should have labeled y-axis.

SCATTERplots <- lapply(
2:8, 
function( column ){
  DataPlot <- ggplot(
    data = NewAuto,
    aes(
      x = mpg,
      y=NewAuto[,column]
    )
  )+geom_point()+facet_grid(.~MPG01)+ylab(names(NewAuto)[column])
  return( DataPlot)  
}
)
do.call( grid.arrange, SCATTERplots) 

Unfortunately I get:

Error in `[.data.frame`(NewAuto, , column) : object 'column' not found

How can I fix this?

I'm a begginer, so please take this into account.

Upvotes: 0

Views: 512

Answers (1)

MrFlick
MrFlick

Reputation: 206616

You can't use variable names within aes. You can only use literal values or names of elements from your data object. You should be using aes_string instead:

aes_string(
  x = "mpg",
  y="column"
)

The reason your's fails is because "NewAuto[,column]" it not a column in NewAuto.

Upvotes: 1

Related Questions