Base R provides a powerful set of tools for creating a variety of static, interactive, and dynamic graphics. In this tutorial, we will explore how to create basic plots using Base R graphics, step by step, in simple terms.

What You Will Learn:

  1. Setting up R
  2. Creating Simple Plots
  3. Customizing Plots
  4. Saving Plots

1. Setting up R

First, ensure that you have R installed on your system. You can download and install R from CRAN.

Once installed, you can open R or RStudio to start working with graphics.

2. Creating Simple Plots

a. Simple Scatter Plot

A scatter plot is used to visualize the relationship between two variables.

# Sample data
x <- c(1, 2, 3, 4, 5)
y <- c(2, 4, 6, 8, 10)

# Creating a scatter plot
plot(x, y)

Output: A simple scatter plot where x and y values are plotted against each other.

b. Line Plot

A line plot is used to show trends over time or sequence.

# Sample data
x <- 1:10
y <- x^2

# Creating a line plot
plot(x, y, type = "l")

Output: A line connecting points in a sequence from 1 to 10, showing the squares.

3. Customizing Plots

a. Adding Titles and Labels

# Adding titles and labels
plot(x, y, main = "Square of Numbers", xlab = "Numbers", ylab = "Squares")

Output: Title “Square of Numbers” with appropriate X and Y axis labels.

b. Changing Colors

# Changing colors
plot(x, y, col = "blue", pch = 19)

Output: A blue scatter plot with filled points.

c. Adding a Legend

# Adding legend
plot(x, y, col = "red", pch = 16)
legend("topright", legend = "Squares", col = "red", pch = 16)

Output: A legend added to the plot indicating that red dots represent squares.

4. Saving Plots

To save the plot as an image file, you can use:

# Saving plot as PNG
png("plot_example.png")
plot(x, y)
dev.off()

This saves the plot as a plot_example.png file.