As mentioned during the session setup, load the following packages using the
library(tidyverse) library(RColorBrewer) library(ghibli) library(palettetown)
To give you an example of how to generally plot in R, using
ggplot2, we can examine the diamonds data set. This is an extremely common example, but is useful to understand how to structure of how to plot.
# Chunk 1 ggplot(data = diamonds, mapping = aes(x = price, y = carat, colour = cut)) + # Chunk 2 geom_point() + # Chunk 3 labs(title = "Diamonds Plot Example", x = "Price", y = "Carat")
We can break down the code for this plot into three Chunks.
ggplot()function, this is the core part of any visualization function, and typically contains information such as specification of the data to be used, and the mapping aesthetics. These details however can also be included within Chunk 2.
geomspecification, details which type of plot you would like to plot. In this case, we are plotting a point chart, or scatter plot.
labs(). In this case, specifying the labels which should be included alongside your plot.
These three components (that is the ggplot function, the geom specification and additional details) are core components of any data visualization. And can be summed up also in the diagram below.
Alternatively, this code can be written as so, and produce the same results.
# Chunk 1 ggplot() + # Chunk 2 geom_point(data = diamonds, mapping = aes(x = price, y = carat, colour = cut)) + # Chunk 3 labs(title = "Diamonds Plot Example", x = "Price", y = "Carat")
Understanding that there are multiple methods of achieving the same result is incredibly important, especially during programming in R.
As you can see, these visualizations are made up of lots of smaller components. These changeable aspects include:
geom_line()- line charts
geom_point()- scatter plots
geom_polygon()- shape diagrams
These are used within the function,
aes = mapping()
theme()- base theme
theme_bw()- black and white theme
theme_void()- empty theme (no scales, legends etc)
theme_minimal()- minimal theme
ylim()- Scale Limits
scale_y_log10()- Log Scales
coord_cartesian()- Cartesian Coordinate System
coord_polar()- Polar Coordinate System
Understanding Polar Coordinates
Coordinates on the x-axis indicate the circular movement.
Coordinates on the y-axis indicate the distance of the points from the origin.
The origin of the plot is defined as the centre of the plot
The plot begins and ends at the top of the plot (before rotating right)
When it comes to applying colour to the plots you produce, there again are multiple ways in which these can be defined. This includes:
Palettes from R Packages
Mathematical Functions in R
For the purpose of this practical, we will only call a select few standardized mathematical functions to help generate our sequences. Below are a list of some of those we will use, and some which I encourage you to explore further.
Logarithmic and Exponential Functions
log(x, base = y)
x ^ 2
x ^ n