R plot() Function - Drawing Scatter Plots

R 语言实例R Language Examples

The R plot() function is the most basic plotting function, used to create various graphics such as scatter plots, line charts, and more.

plot() is the entry point of the R graphics system; almost all visualizations start from it.

The syntax format of the plot() function is as follows:

plot(x, y, type = "p", main = "", xlab = "", ylab = "", col = "black")

Parameter description:

  • x, yThe coordinates of the data points.

  • typeGraph type: "p" (points), "l" (lines), "b" (both points and lines), "o" (overlaid).

  • mainThe graph title.

  • xlab, ylabThe x-axis and y-axis labels.

  • colColor.

Example

# Create data
height <- c(160, 165, 170, 175, 180, 158, 172, 168, 178, 182)
weight <- c(55, 60, 65, 70, 80, 52, 68, 62, 75, 85)

# Draw scatter plot
plot(height, weight,
     main = "Relationship between height and weight",
     xlab = "Height (cm)",
     ylab = "Weight (kg)",
     col = "blue",
     pch = 16)  # pch=16 is a solid dot

# Add trend line
abline(lm(weight ~ height), col = "red", lwd = 2)

Running the above code will display a scatter plot and a red trend line.

plot() can also be used directly on data frames, automatically generating a scatter plot matrix between variables:

Example

# View the relationships between variables in the iris dataset
print("iris scatter plot matrix:")
plot(iris[, 1:4],
     col = iris$Species,
     main = "Iris dataset scatter plot matrix")

Running the above code will generate a 4x4 scatter plot matrix, where points of different colors represent different iris species.

R 语言实例R Language Examples

Other extensions