The function plot()
Basic Syntax of plot()
The basic syntax of plot() is:
plot(x, y, type = "p", main = NULL, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, pch = NULL, col = NULL, lty = NULL, lwd = NULL, cex = NULL, ... )
- x, y: Data vectors for the X and Y axes.
- type: Type of plot (“p” for points, “l” for lines, “b” for both points and lines, etc.).
- main: Title of the plot.
- xlab, ylab: Labels for the X and Y axes.
- xlim, ylim: Limits for the X and Y axes.
- pch: Symbol used for points.
- col: Color of points or lines.
- lty: Line type (1 for solid, 2 for dashed, etc.).
- lwd: Line width.
- cex: Text or point size scaling.
- …: Additional arguments to customize the plot.
Detailed Examples
Scatter Plot
x <- 1:10 y <- x^2 # Basic scatter plot with blue points plot(x, y, type = "p", main = "Scatter Plot", xlab = "X", ylab = "Y", pch = 19, col = "blue")
- type = “p”: Points only.
- pch = 19: Filled circles.
- col = “blue”: Point color.
Line Plot
# Line plot with a red line plot(x, y, type = "l", main = "Line Plot", xlab = "X", ylab = "Y", col = "red", lwd = 2)
- type = “l”: Lines only.
- col = “red”: Line color.
- lwd = 2: Line width.
Plot with Points and Lines
# Plot with both points and lines plot(x, y, type = "b", main = "Plot with Points and Lines", xlab = "X", ylab = "Y", pch = 17, col = "green", lty = 1)
- type = “b”: Both points and lines.
- pch = 17: Triangle symbols.
- col = “green”: Color of points and lines.
Plot with Custom Limits
# Plot with customized axis limits plot(x, y, type = "b", main = "Plot with Custom Limits", xlab = "X", ylab = "Y", xlim = c(0, 12), ylim = c(0, 120), col = "purple", lty = 2, lwd = 1.5)
- xlim = c(0, 12): X-axis limits from 0 to 12.
- ylim = c(0, 120): Y-axis limits from 0 to 120.
- lty = 2: Dashed line.
- lwd = 1.5: Line width.
Plot with Text and Annotations
# Plot with text annotations plot(x, y, type = "b", main = "Plot with Annotations", xlab = "X", ylab = "Y", col = "orange") text(x, y, labels = round(y, 1), pos = 3, cex = 0.8, col = "blue")
- text(x, y, labels, pos, cex, col): Adds text to points.
- labels = round(y, 1): Text near points.
- pos = 3: Text above points.
- cex = 0.8: Text size.
- col = “blue”: Text color.
Multi-Dimensional Plots with plot()
For more complex plots, you can use plot() in combination with other functions or explore packages like ggplot2 for advanced plotting.
Additional Notes
- par(): Used to set graphical parameters such as margins, layout. For example, par(mfrow = c(2, 2)) divides the plotting area into a 2×2 grid.
- axis() and legend(): Add customized axes and legends.
Post Views: 81