install.packages(ggplot2)
library(ggplot2)
library(repr)
# data
data(mtcars)
# Convert cyl to a factor
mtcars$cyl <- as.factor(mtcars$cyl)
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
str(mtcars)
## 'data.frame': 32 obs. of 11 variables:
## $ mpg : num 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
## $ cyl : Factor w/ 3 levels "4","6","8": 2 2 1 2 3 2 3 1 1 2 ...
## $ disp: num 160 160 108 258 360 ...
## $ hp : num 110 110 93 110 175 105 245 62 95 123 ...
## $ drat: num 3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
## $ wt : num 2.62 2.88 2.32 3.21 3.44 ...
## $ qsec: num 16.5 17 18.6 19.4 17 ...
## $ vs : num 0 0 1 1 0 1 0 1 1 1 ...
## $ am : num 1 1 1 0 0 0 0 0 0 0 ...
## $ gear: num 4 4 4 3 3 3 3 4 4 4 ...
## $ carb: num 4 4 1 1 2 1 4 2 2 4 ...
In some cases, you will want to create a quick plot. So, you may prefer to use qplot() over ggplot(). The qplot() is very similar to the basic R plot() function.
A simplified format of qplot() is :
qplot(x, y = NULL, data, geom=“auto”)
#Basic Scatter Plot
qplot(mpg,wt,data=mtcars)#plot command
qplot(mpg,wt,data=mtcars, geom = "point")
qplot( mpg,wt,data = mtcars,geom =c("point","smooth"))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'
The following R code will change the color and the shape of points by groups
q1<-qplot(mpg, wt, data = mtcars, colour = cyl)
q2<-qplot(mpg, wt, data = mtcars, colour = I("blue"))
q3<-qplot(mpg, wt, data = mtcars, colour = I(2))
library(ggpubr)
ggarrange(q1,q2,q3 , ncol = 3, nrow = 1)
#install.packages("gridExtra") # Install #gridExtra package
#library("gridExtra")
#grid.arrange(q1, q2,q3, ncol = 3)
#gridExtra::grid.arrange(q1,q2,q3)
#ggarrange(q1, q2, q3 )
q4<-qplot(mpg, wt, data = mtcars, colour = cyl, shape = cyl)
q5<-qplot(mpg, wt, data = mtcars, size = cyl )
mod <- lm(mpg ~ wt, data = mtcars)
q6<-qplot(resid(mod), fitted(mod))
ggarrange(q4,q5,q6 , ncol = 3, nrow = 1)
## Warning: Using size for a discrete variable is not advised.
# Use different geoms
qplot(mpg, wt, data = mtcars, geom = "path")
After creating plots, two other important functions are: last_plot() which returns the last plot
ggsave
(“myplot.png”, width = 5, height = 5), which saves the last plot in the current working directory.
Additional Readings
(1)R Programming For Beginners Part 1
https://www.youtube.com/watch?v=DmX5TW473BA (2)R tutorial by examples:Data Frame
https://rpubs.com/sheikh/data_frame
(3)Data Manipulation with dplyr using Covid19 Data
https://rpubs.com/sheikh/dplyr
(4)R Tutorial:Graphs using qplot
https://rpubs.com/sheikh/qplot