# Statistical Methods in Medical Research - Laaketieteellisen tutkimuksen tilastolliset menetelmat
# At University of Helsinki
# 23.9.2021
# Matti Pirinen
###
### 7. Learn R: Plotting part II
###
# Let's go through more of the basic plotting options.
# Let's generate data with n=10 points from two Normal distributions
set.seed(11) #initialize random number generator
n = 10
x = rnorm(n, rep(c(-1,3), each = n/2), 1) #means are -1 for first 5 and +3 for last 5; sd = 1 for all
y = rnorm(n, rep(c(-1,1), each = n/2), 1) #means are -1 for first 5 and +1 for last 5; sd = 1 for all
plot(x,y)
#We can give different color and style for every point in the plot
# by making 'col=' and 'pch=' vectors of length n
#Let's use blue dots for 1,...,5 and red triangles for 6,...,10.
plot(x, y, col = rep(c("steelblue","firebrick"), each = n/2),
pch = rep(c(19, 17), each = n/2))
#Command:
colors()
#lists some ready made colors and you can see them for example here:
# https://www.datanovia.com/en/blog/awesome-list-of-657-r-color-names/
#The possible pch styles are here:
# https://www.datanovia.com/en/blog/pch-in-r-best-tips/
#Once plot exist, we can add things to it, rather than always drawing a new plot
#ADDING STRAIGHT LINES
#Let's add line y = 2*x-2
abline(a = -2, b = 2, col = "black", lty = 2) #lty = 2 is a dashed line
#Let add horizontal line at y = 0
abline(h = 0, col = "gray", lty = 3)
#Let's add vertical line at x = 1
abline(v = 1, col = "gray", lty = 3)
#ADDING GRID ON BACKGROUND
grid()
#ADDING TEXT to given x-y coordinate positions
text(x = c(2,-1.2), y = c(1.2,-2), c("A", "B"), col = c("limegreen","tomato"))
#This way you can label individual points, for example
#ADDING LINE SEGMENTS
#We can add segments connecting a set of x and y coordinates by lines(x,y)
lines(x = c(-2,-2,2,2), y = c(0,-1,-1,-2), lty = 1)
#This is also a good option for adding graphs of functions as long as we have
# small enough intervals between x-coordinates (See Lecture 4)
#ADDING POINTS
#Let's add points at (0,0), (0,1)
points(x = c(0,1), y = c(0,0), pch = 18, col = "orange", cex = 1.4)
#ADDING LEGEND
#We can add legend to four corners, such as "bottomright" or "topleft" (or to any x-y position)
#Let's add line legend to topleft
#pch for lines can be -1, although would not be needed here since only lines are included in this legend
legend("topleft", legend = c("line", "dashed"), cex = 0.85,
pch = c(-1, -1), lty = c(1, 2), col = c("black", "black"))
#And point legend to bottomright
#lty for non-line symbols are 0, although wouldn't be needed in this legend since only points are present
legend("bottomright", legend = c("dots","tris", "extra"), cex = 0.85,
pch = c(19, 17, 18), lty = c(0, 0, 0), col = c("steelblue", "firebrick", "orange"))
#you may need to adjust cex to get it as suitably sized for your purpose