R Module 4
R Module 4
Syntax:
ggplot(mpg) + geom_point(aes(x = displ, y = hwy))
ggplot(mpg, aes(x = displ, y = hwy) + geom_point()
• Pay attention with the “+” sign, this means we added new layer. As we
learn more about ggplot2 we will make more sophisticated plots.
Grammar of Graphics
• Layer
• Data
• Mapping
• Statistical transformation (stat)
• Geometric object (geom)
• Position adjustment (position)
• Scale
• Coordinate system (coord)
• Faceting (facet)
• Defaults
• Data
• Mapping
Aesthetic Attributes
• We can plot by certain categories by using aesthetics, for example:
• This gives each point a unique attribute corresponding to its class. The
legend allows us to read data values from the attributes
Plot
1 2 3
Facet Wrap
• Another technique for displaying additional categorical variable on a
plot is faceting. It splits the data into subsets and displaying the same
graph for each subset, or example:
#Add size
ggplot(data=movies, aes(x=CriticRating, y=AudienceRating,
colour=Genre, size=BudgetMillions)) +
geom_point()
R Practice Session
• # Plotting with Layers
• p <- ggplot(data=movies, aes(x=CriticRating, y=AudienceRating,
• colour=Genre, size=BudgetMillions)) +
• geom_point()
• #Point
• p + geom_point()
• #Lines
• p+geom_line()
• #Multiple Layers
• p+geom_point() + geom_line()
• p+geom_line() + geom_point()
Post-tutorial Assignment
Tutorial Assignment
You have been supplied with mpg data.
Please create five plots depicting:
1. Create a basic plot using this criteria : x = cty and y = hwy
2. Create a basic plot using : x = displ, y = cyl and color of Blue
3. Create a violin-shape plot using x=displ, y = cyl and color fill of Red.
4. Try to map a plot using x=cty, y=displ, color based on types of
“manufacturer” and give a title of the graph (“A point geom with
position and color aes”)
Tutorial Assignment
1. Using the diamond data:
• Please create a ggplot similar to the previous sample but with x=carat,
y=depth, alpha of 0,15, title of x axis “The Carat of Diamond”, title of y
axis “The Depth of Diamond” and ggplot title of “Depth and Carat of
the Diamonds over Cut”. Make the legend position on the top of the
graph.
You need to submit the Homework to obtain a training certificate!
References
• Https://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf
• Eremenko, Kiriil. (2021, March 5). R For Data Science with Real
Exercise [Video file]. Retrieved from
https://www.udemy.com/course/r-programming/learn/lecture/45857
02#overview
.
• https://www.statmethods.net/input/importingdata.html
Thank You and See you on the next tutorial!