Base Graphics in R
Introduction
Base graphics is the default graphics system in R, providing a set of functions for creating a wide variety of plots. This system allows users to easily visualize data through scatter plots, line graphs, histograms, and more. In this tutorial, we will explore the fundamental concepts and functions of base graphics in R.
Getting Started
To use base graphics, you first need to install R and RStudio. Once installed, you can start creating plots using built-in datasets or your own data.
Let's load a sample dataset:
The mtcars
dataset contains information about various car models.
Basic Plotting
The simplest way to create a plot in base graphics is using the plot()
function. Here’s how you can create a scatter plot of miles per gallon (mpg) against horsepower (hp):
This command generates a scatter plot with hp
on the x-axis and mpg
on the y-axis. You can customize the title and labels accordingly.
Customizing Plots
You can customize various aspects of your plot using additional parameters in the plot()
function. For example, changing the point type and color:
In this example, pch=19
specifies the point type (solid circle), and col="blue"
sets the color of the points to blue.
Adding Lines and Text
You can add lines and text annotations to your plots using abline()
and text()
functions. Here’s how to add a regression line:
This code first plots the scatterplot and then adds a regression line in blue.
Saving Your Plots
You can save your plots to files using functions like png()
, jpeg()
, or pdf()
. For example, to save a plot as a PNG file:
In this example, png("scatterplot.png")
initiates the creation of a PNG file, and dev.off()
closes the device.
Conclusion
Base graphics in R provides a powerful and flexible way to visualize data. By mastering the functions and customization options available, you can create informative and visually appealing graphics for your data analysis. Experiment with different datasets and plot types to enhance your data visualization skills in R.