Base R provides built-in functions to create a variety of plots and visualizations without the need for additional packages. These functions are essential for quickly exploring and presenting your data.
1. Plotting with plot()
The plot() function is the most versatile base R plotting function. It can be used for scatter plots, line plots, and more.
# Scatter plot
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 6, 8, 10)
plot(x, y, main="Scatter Plot", xlab="X Axis", ylab="Y Axis", col="blue", pch=19)
Parameters:
main: Plot titlexlab,ylab: Axis labelscol: Color of pointspch: Point type
2. Line Plots with type=”l”
plot(x, y, type="l", main="Line Plot", col="red", lwd=2)
Parameters:
type="l": Line plotlwd: Line width
3. Histogram with hist()
Histograms show the distribution of a numeric variable:
scores <- c(90, 85, 88, 92, 75, 80, 95)
hist(scores, main="Score Distribution", xlab="Scores", col="lightgreen", breaks=5)
Parameters:
breaks: Number of binscol: Fill color
4. Boxplot with boxplot()
Boxplots show data spread, median, and outliers:
boxplot(scores, main="Score Boxplot", ylab="Scores", col="orange")
5. Bar Plot with barplot()
Bar plots visualize categorical data counts or values:
names <- c("Alice", "Bob", "Charlie")
heights <- c(5, 7, 6)
barplot(heights, names.arg=names, main="Bar Plot Example", col="skyblue")
6. Adding Customizations
You can enhance plots using additional functions:
plot(x, y, main="Customized Plot", xlab="X", ylab="Y", col="purple", pch=16)
abline(h=5, col="red", lty=2) # Add horizontal line
abline(v=3, col="green", lty=3) # Add vertical line
text(4, 8, "Point (4,8)", col="blue") # Add text annotation
7. Multiple Plots with par()
To display multiple plots in one window:
par(mfrow=c(2,2)) # 2x2 layout
plot(x, y)
hist(scores)
boxplot(scores)
barplot(heights, names.arg=names)
par(mfrow=c(1,1)) # Reset layout
Conclusion
Base R plotting functions are simple yet powerful tools for quick data visualization. Functions like plot(), hist(), boxplot(), and barplot() allow you to explore your data and present results effectively. Mastering these functions lays the foundation for more advanced plotting with packages like ggplot2.