Visualizing Scatterplots in R | Correlation

Introduction

Scatterplots are a first step for examining the form, direction, and spread of an association between two quantitative variables. This tutorial builds individual plots and a scatterplot matrix in R. The visual pattern should guide analysis, not be treated as evidence of causation.

Import data set

Before importing data, confirm that the current project contains no unsaved objects you need to retain. Clearing the workspace is optional; closing graphics devices and clearing the console do not improve the statistical quality of the analysis.

rm(list = ls(all = TRUE))
graphics.off()
shell("cls")

The example uses the same data set as the preceding correlation tutorial. Follow the linked post for the full variable definitions and study context, and verify that both posts use the same version of the file.

Read the CSV file with read.csv(), using the correct path and setting header = TRUE when the first row contains variable names. Then check the column names, dimensions, variable types, and missing values.

Note that file paths are specified using slashes (/). In R, you cannot use backslashes (\), as you would in Microsoft Windows, unless you replace it with forward-slash (/) or double all the backslashes (\\). 
data <- read.csv(file = "E:/Youtube Channel/Agron Info Tech/Lectures/Data Analysis/34 Correlation analysis in R/data_corr.csv", 
                 header = TRUE)
head(data, 3)
#   rep method priming em.head head.mat plant.height total.tillers th.kernal.wt
# 1   1   conv      NP      88       35          113           445          9.9
# 2   1   conv      HP      92       27          126           498         12.0
# 3   1   conv      OP      83       27          118           535         15.7
#   kernal.yield straw.yield harvest.index
# 1         3.46        12.9          26.8
# 2         3.58        13.3          26.9
# 3         3.61        13.9          26.0

Use head(), str(), or a data viewer to inspect the imported object. The fix() function opens an editable data window; use it cautiously and prefer correcting the source file or applying explicit transformations in a script so changes are reproducible.

fix(data)
Data editor window for fix(data) command

The original example uses attach() for convenient column access. In a reusable analysis, refer to columns through the data frame or supply data = to the plotting function to avoid name masking.

We will plot two quantitative variables to inspect their observed relationship. Check measurement units, unusual values, and the number of complete pairs before fitting a trend line or calculating a correlation.

attach(data)

Now let’s proceed further to visualize a scatterplot between two variables to see how one variable is affected by the other.

Visualizing Scatterplots

Scatterplot between two variables

The ggpubr package provides ggscatter() for ggplot-based scatterplots. Install the package once if needed, then load it in the current R session. Keep package installation separate from the analysis script used to reproduce the figure.

library(ggpubr)
# Loading required package: ggplot2
# install.pakcages("ggpubr")
# install.pakcages("backports")

If installation reports a missing dependency, read the full error message and install or update the named package from a trusted repository. Package dependency errors can reflect version conflicts, so avoid assuming that one specific dependency fix applies to every system.

Error message while installing ggpubr package

Error message while installing ggpubr package

Use ggscatter() with the data frame and the names of the x- and y-variables. Add informative axis labels with units, and check that the selected columns are numeric. A clear point cloud is the starting point for assessing form, direction, and possible influential observations.

ggscatter(
          data = data,
          x = "total.tillers", 
          y = "kernal.yield",
          xlab = "Number of tillers",
          ylab = "Kernal yield in rice"
          )

A fitted trend line can help summarize a pattern, but it does not replace inspection of the points or model diagnostics. Use the add argument to overlay a line that matches the relationship you intend to describe.

A linear regression line summarizes a straight-line trend; a LOESS curve provides a flexible local smooth. The choice should follow the scientific question and data pattern. A smooth is descriptive and should not be presented as a prespecified inferential model unless its uncertainty and fitting procedure are addressed.

A confidence band can be added around the fitted line. State what the band represents and which confidence level was used. It reflects uncertainty in the estimated mean trend under the fitted model, not the range expected for individual observations.

ggscatter(
          data = data,
          x = "total.tillers", 
          y = "kernal.yield",
          xlab = "Number of tillers",
          ylab = "Kernal yield in rice",
          add = "reg.line", # "loess" for local regression fitting
          )

Use add.params to adjust the line and band appearance, and set correlation annotations only when the selected method is appropriate. Pearson correlation summarizes linear association; Spearman summarizes monotonic rank association. If points are colored by a group, report the grouping variable and avoid interpreting a pooled correlation when group structure may alter the pattern.

To add a confidence interval around this regression line we can use conf.int argument. We can set a logical value to this argument. Setting TRUE value for this argument will add confidence interval as shaded region along the regression line. The default level controlling confidence interval is \(95%\). Often researchers choose \(90%\), \(95%\) or \(99%\) confidence levels and you can set this value in conf.int.level argument.

We can further customize this regression line by using add.params argument. By using this argument you can specify color of the regression line and the shaded region, size of the line, linetype of regression fitting and fill color of the points.

ggscatter(
          data = data,
          x = "total.tillers", 
          y = "kernal.yield",
          xlab = "Number of tillers",
          ylab = "Kernal yield in rice",
          add = "reg.line",
          conf.int = TRUE,
          conf.int.level = 0.95,
          add.params = list(color = "black",
                            size = 1,
                            linetype = 1,
                            fill = "lightgray"))

Now let’s add correlation coefficient and probability values to this plot. You can add these values to scatterplot by setting TRUE value for cor.coef argument. Also specify the correlation method in cor.method argument as I am using “pearson” which is most commonly used method. You can see the values are printed in a single line. We can write these values in two separate line by setting “” character as value for label.sep argument. Further you can also show grouping variable in most of the cases also called factor variable by using color argument. Type the grouping variable name as character string in this argument. You can also customize the color of the points by using palette argument where you can specify the color of your choice for each level of the grouping variable. This will create an elegant style scatterplot.

ggscatter(
          data = data,
          x = "total.tillers", 
          y = "kernal.yield",
          xlab = "Number of tillers",
          ylab = "Kernal yield in rice",
          add = "reg.line",
          conf.int = TRUE,
          conf.int.level = 0.95,
          add.params = list(color = "black",
                            size = 1,
                            linetype = 1,
                            fill = "lightgray"),
          cor.coef = TRUE, cor.method = "pearson",
          cor.coeff.args = list(label.sep = "\n"), # Correlation and probability value
          color = "priming",                       # Custom color palettes
          palette = c("#00AFBB", "#E7B800", "#FC4E07"))

Comments

  1. whare is path coefficient analysis script?

    ReplyDelete

Post a Comment