-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPlotCorrelation_line.R
61 lines (53 loc) · 2.15 KB
/
PlotCorrelation_line.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# Script name: PlotCorrelation_line.R
#
# Author: Caroline Nettekoven, 2021
# Contact: [email protected]
#
# Description: Function to plot correlation between two variables.
# Plots regression line if correlation is significant at
# p < .05.
#
# Parameters:
#
# data Dataframe with the two variables to be correlated.
#
# results Results of correlation.
# Object is in the format of the output from the "rcorr"
# function from the Hmisc package.
#
# X Variable name of x-variable (must match column name in data)
# Y Variable name of y-variable (must match column name in data)
#
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# --------------------------------------------------------------------
PlotCorrelation_line <- function(data, results, X, Y) {
source("/Users/CN/Documents/repos/my_scripts/r/flattenCorrMatrix.R")
library(ggthemes)
flat <- flattenCorrMatrix(results$r, results$P)
# Find relevant rows
selectedRows <- flat[grep(paste(X), flat$row), ]
selectedRow <- selectedRows[grep(paste(Y), selectedRows$column), ]
r <- selectedRow$cor
p <- selectedRow$p
xValues <- data[ , which(colnames(data)==paste(X))]
yValues <- data[ , which(colnames(data)==paste(Y))]
plotdata <- data.frame(xValues, yValues)
if (p<0.05) {
currentplot <- ggplot(plotdata, aes(x=xValues, y=yValues)) +
geom_point(color="black") +
geom_smooth(method=lm, se=TRUE, color="black") +
theme_tufte(base_size = 15, base_family = "serif") +
geom_rangeframe() # + ggtitle(paste("p = ", round(p,4), "R = ", round(r,4)))
} else {
currentplot <- ggplot(plotdata, aes(x=xValues, y=yValues)) +
geom_point(color="black") +
theme_tufte(base_size = 15, base_family = "serif") +
geom_rangeframe()
}
# Add Labels
print(currentplot + labs(y=paste(Y), x = paste(X), size=5))
# Print results
paste("R = ", round(r,4), "p = ", round(p,4))
}