R Scatterplot

Scatterplots in R are used to visualize the relationship between two continuous variables. The plot() function creates a scatterplot by default.

Key Topics

Scatterplot Example

# Creating a scatterplot
x <- c(1, 2, 3, 4, 5)
y <- c(5, 3, 8, 6, 10)

plot(x, y, main = "Scatterplot", xlab = "X-axis", ylab = "Y-axis", pch = 19)

Output:

A scatterplot with points plotted at (1, 5), (2, 3), (3, 8), (4, 6), and (5, 10).

Code Explanation: The plot() function creates a scatterplot with the specified x and y values. The pch parameter changes the shape of the points.

Adding a Trendline

You can add a trendline to a scatterplot using the abline() function.

# Adding a trendline
model <- lm(y ~ x)  # Linear model
plot(x, y, main = "Scatterplot with Trendline", xlab = "X-axis", ylab = "Y-axis", pch = 19)
abline(model, col = "blue")

Output:

A scatterplot with a blue trendline fitted to the data.

Code Explanation: The lm() function creates a linear model, and abline() adds a trendline to the scatterplot.

Key Takeaways

  • Scatterplots are created using the plot() function by default.
  • Use the pch parameter to change point shapes.
  • Add a trendline using the lm() and abline() functions.