2
votes

I'm a beginner with R going over the ggplot2 tutorial and something has caught my eye as being bizarre when using the mtcars dataset.

For example, consider the following:

>library(ggplot2)
>g<-ggplot(mpg, aes(class)) + geom_bar()
>g

I can't figure out why this works. This clearly makes a plot with the counts of each car class (2seater, compact, midsize, minivan, pickup, subcompact, suv).

My question is: How does R/ggplot know what classes these cars are in? There is no variable in the mtcars data.frame that describes this:

>mtcars$class
NULL

Is this something just built into the ggplot package?

1
try with mpg$classHubertL
You're using the mpg data frame in your ggplot code, not the mtcars data frame. The mpg data frame is built into the ggplot2 package (run data(package="ggplot2")), while the mtcars data frame is included in base R.eipi10
@eipi10 your comment is the answer, and should be posted as such.mnel

1 Answers

1
votes

You're using the mpg data frame in your ggplot code, not the mtcars data frame. Your code is:

ggplot(mpg, aes(class)) + geom_bar()

mpg is the data argument. But if you change to

ggplot(mtcars, aes(class)) + geom_bar() 

you'll get an error, because the mtcars data frame does not have a column called class.

The mpg data frame is built into the ggplot2 package. Run data(package="ggplot2") to see which data sets come with ggplot2. The mtcars data frame is included in base R. Run data() to see data sets available from all loaded packages.