library(ggplot2)
suppressWarnings(suppressMessages(library(ggplot2)))
#————————————————————————– # Data set from the package ggplot2
data(package="ggplot2")
auto_data=ggplot2::mpg #load the data
str(auto_data)
## tibble [234 × 11] (S3: tbl_df/tbl/data.frame)
## $ manufacturer: chr [1:234] "audi" "audi" "audi" "audi" ...
## $ model : chr [1:234] "a4" "a4" "a4" "a4" ...
## $ displ : num [1:234] 1.8 1.8 2 2 2.8 2.8 3.1 1.8 1.8 2 ...
## $ year : int [1:234] 1999 1999 2008 2008 1999 1999 2008 1999 1999 2008 ...
## $ cyl : int [1:234] 4 4 4 4 6 6 6 4 4 4 ...
## $ trans : chr [1:234] "auto(l5)" "manual(m5)" "manual(m6)" "auto(av)" ...
## $ drv : chr [1:234] "f" "f" "f" "f" ...
## $ cty : int [1:234] 18 21 20 21 16 18 18 18 16 20 ...
## $ hwy : int [1:234] 29 29 31 30 26 26 27 26 25 28 ...
## $ fl : chr [1:234] "p" "p" "p" "p" ...
## $ class : chr [1:234] "compact" "compact" "compact" "compact" ...
#convert int to char
auto_data$year_C=as.factor(auto_data$year)
auto_data$cyl_C=as.factor(auto_data$cyl)
#--------------------------------------------------------------------------
# Initial ggplot
#Plot a single metric / numeric variable,
#for example, "cty"
#We require an index set to create the plot
#So we consider number of rows - use nrow(auto_data)
n=nrow(auto_data)
rowind = seq(1,n) #alternate to 1:n is the function seq()
#Layer 2 Choosing a geometry to plot
# here we use points
ggplot(auto_data, aes(x=rowind,y=cty)) +
geom_point()
#Layer 3 aesthetics to plot
#Three options: size, shape, color
ggplot(auto_data, aes(x=rowind,y=cty)) +
geom_point(size=5)