Home > Back-end >  Data relation in R plot
Data relation in R plot

Time:08-24

I have a data set in R, i.e the Iris dataset and I plot the first variable against all others with the following code

library(datasets)
data(iris)
df <- iris
par(mfrow = c(2, 2))
for (i in seq(ncol(df))[-1]) {
  plot(df[, 1], df[, i], xlim=range(5.5:8),xlab = colnames(df)[i],ylab = "Y")
  }

I use the xlim to remove data that do not display a specific pattern. How can I include a line/curve that shows the relation of the data, (i.e to display a linear relationship or an exponential). Is there any other way to make the plots more "presentable" but still displaying the relation of the data?

CodePudding user response:

You can use abline to show a linear regression line of the function lm using the following code:

df <- iris
par(mfrow = c(2, 2))
for (i in seq(ncol(df))[-1]) {
  # plt
  plot(df[, 1], df[, i], xlim=range(5.5:8), xlab = colnames(df)[i],ylab = "Y")
  # Add regression line
  abline(lm(df[, i] ~ df[, 1], data = df), col = "red")
}

Created on 2022-08-24 with reprex v2.0.2

  • Related