R Markdown

Question: How do I make a scatterplot in R and draw lines from the origin to two points?

Data

We’ll use the “ggplot2” and “ggpubr” packages to address this question. You’ll need to install the package with install.packages(“ggplot2”) or install.packages(“ggpubr”) if you have not done so before, call the library(“ggplot2”) and library(“ggpubr”) and load the data with data(msleep)

library(ggplot2)
library(ggpubr)
data(msleep)

We’ll create new columns in the dataframe.

msleep$brainwt_log <- log(msleep$brainwt)

msleep$bodywt_log <- log(msleep$bodywt)

We can create a scatter plot that compares the log of brain weight for a species versus the log of body weight.I used the summary function to get the x and y coordinates of the min and max points.

The segments function lets me draw a line from the orgin to the min and max points by adding their x and y coordinates.

plot(y = msleep$brainwt_log,
          x = msleep$bodywt_log)

summary(msleep$bodywt_log)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
## -5.2983 -1.7600  0.5128  0.8433  3.7118  8.8030
summary(msleep$brainwt_log)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max.    NA's 
##  -8.874  -5.845  -4.390  -4.063  -2.085   1.743      27
segments(x0 = -7, y0 = -10, x1 = -5.2983, y1 = -8.874,  col = "darkgreen" )
segments(x0 = -7, y0 = -10, x1 = 8.8030 , y1 = 1.743,  col = "darkgreen" )