Visualizations with ggplot2
ggplot2 is a popular library for creating stunning graphics with R. It has some advantages over the basic plotting system in R, mainly consistent use of function arguments and flexible plot alteration. ggplot2 is an implementation of Leland Wilkinson's Grammar of Graphics — a general scheme for data visualization.
In ggplot2, plots may be created via the convenience function qplot()
where arguments and defaults are meant to be similar to base R's plot()
function. More complex plotting capacity is available via ggplot()
, which exposes the user to more explicit elements of the grammar. (from wikipedia)
RStudio has a cheatsheet for data visualization with ggplot2.
This exercise is part of the course
Helsinki Open Data Science
Exercise instructions
- Access the ggplot2 library
- Initialize the plot with data and aesthetic mappings
- Adjust the plot initialization: Add an aesthetic element to the plot by defining
col = gender
insideaes()
. - Define the visualization type (points)
- Draw the plot to see how it looks at this point
- Add a regression line to the plot
- Add the title "Student's attitude versus exam points" with
ggtitle("<insert title here>")
to the plot with regression line - Draw the plot again to see the changes
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# learning2014 is available
# Access the gglot2 library
library(ggplot2)
# initialize plot with data and aesthetic mapping
p1 <- ggplot(learning2014, aes(x = attitude, y = points))
# define the visualization type (points)
p2 <- p1 + geom_point()
# draw the plot
p2
# add a regression line
p3 <- p2 + geom_smooth(method = "lm")
# add a main title and draw the plot
p4 <- "change me!"