R by Example: Plotting
Creating data visualizations with this code example demonstrating base R plot function for scatter and line plots, layered graphics using lines and legend functions, customization parameters for colors and styles, and histogram generation.
Code
# Generate data
x <- seq(0, 2*pi, length.out = 100)
y <- sin(x)
# Basic scatter plot
plot(x, y,
main = "Sine Wave",
xlab = "Time",
ylab = "Amplitude",
col = "blue",
type = "l", # 'l' for line, 'p' for points
lwd = 2) # Line width
# Adding elements
lines(x, cos(x), col = "red", lty = 2) # Dashed line
legend("topright",
legend = c("Sin", "Cos"),
col = c("blue", "red"),
lty = 1:2)
# Histogram
hist(rnorm(1000), main = "Normal Distribution", col = "lightblue")Explanation
R's base graphics system provides a polymorphic plot() function that produces different visualizations depending on the input object type. For numeric vectors, it creates scatter plots, while for other objects like linear models or time series, it generates appropriate diagnostic or time series plots. The function accepts numerous parameters for customization including main for titles, xlab/ylab for axis labels, col for colors, type for plot type, and lwd for line width.
Base R graphics use a layering system where plots are built incrementally. The initial plot() call creates the graphics device and draws the primary data, then low-level functions like lines(), points(), text(), abline(), and legend() add elements to the existing canvas. These functions modify the current plot rather than creating new ones, allowing complex multi-layer visualizations. The par() function controls global graphics parameters affecting all subsequent plots.
While base graphics excel at quick exploratory visualization, the ggplot2 package has become the standard for publication-quality graphics in R. Built on the Grammar of Graphics framework, ggplot2 uses a declarative syntax with ggplot() initialization, aesthetic mappings via aes(), geometric objects like geom_point() and geom_line(), and layering using the + operator. Despite this, base R plotting remains fundamental for understanding R graphics and is still widely used for simple visualizations.
Code Breakdown
plot(x, y, ...) initializes graphics device and draws primary data.type = "l" specifies line plot; "p" for points, "b" for both.lines() adds secondary data series to existing plot canvas.hist() creates histogram with automatic bin calculation from data.
