Visualizing Data in R with Default Package:
Modified Plot

Somsak Chanaim

International College of Digital Innovation, CMU

October 30, 2024

Modifying a Plot

Modifying a plot in the base R package can be done using various parameters within the plot() function, as well as adding additional elements using other base plotting functions like lines(), points(), abline(), text(), legend(), etc.

Here’s a guide on how to modify different aspects of a plot in base R:

1. Modifying Axes

  • Custom Axis Labels: Use xlab and ylab to modify the axis labels.

  • Custom Axis Limits: Use xlim and ylim to set the limits of the x and y axes.

  • Custom Axis Ticks: Use axis() to customize the ticks and labels.

2. Modifying Points

  • Point Shape: Use pch to change the shape of the points.

  • Point Size: Use cex to change the size of the points.

  • Point Color: Use col to change the color of the points.

Change the Shape of the Points (pch)

Note: The pch = 0 is useless, then we will not consider on this value.

The pch = 15 to 20 are useful for the argument col.

3. Adding Titles and Subtitles

  • Main Title: Use main to add a main title.

  • Subtitle: Use sub to add a subtitle.

4. Adding a Grid

  • Adding Grid Lines: Use grid() to add grid lines to the plot.

5. Adding Lines

  • Adding a Line through Points: Use lines() to add a line connecting points.

  • Adding a Regression Line: Use abline() to add a regression line.

6. Adding Text Annotations

  • Adding Text: Use text() to add text annotations to specific points.

  • Positioning Text: Use pos, adj, and offset to control the position of the text.

7. Adding Legends

  • Adding a Legend: Use legend() to add a legend to the plot.

8. Customizing Plot Margins

  • Custom Margins: Use par(mar = c(bottom, left, top, right)) to adjust the margins.

9. Adding Custom Axes

  • Suppress Default Axes: Use axes = FALSE in plot() and add custom axes with axis().

10. Modified the background color

We can modify the background color of a base R plot using the bg parameter within the par() function.

Explanation:

  • par(bg = "lightblue"): This sets the background color of the plot to light blue.

  • par(bg = "white"): This resets the background color to white for subsequent plots, ensuring that only the current plot is affected.

You can replace “lightblue” with any valid color name or hexadecimal color code (e.g., “#FFD700” for lightblue) to customize the background color as desired.

  • If we want a transparent background color, we can set bg = NULL.

11. Changing the Background Color of the Plot Area

In a base R plot, you can use the rect() function after creating the plot.

Explanation:

  • plot(..., type = "n"): Creates an empty plot with the axes and labels but without plotting the data points.

  • rect(...): Draws a rectangle that covers the entire plot area using the coordinates obtained from par("usr"). The col parameter sets the background color, and border = NA removes the border around the rectangle.

  • points(): Adds the data points on top of the custom background.

12. Changing the Background Color of the Plot Area and Adding Grid Lines

13.1 Multiple Plots in a Row Layout (Using mfrow)

The mfrow parameter arranges plots in a row-wise manner.

13.2 Multiple Plots in a Column Layout (Using mfcol)

The mfcol parameter arranges plots in a column-wise manner.

13.3 Custom Layouts Using layout()

For more complex layouts, you can use the layout() function, which allows for custom arrangements, including varying plot sizes.

Exercise

Exercise 1: Changing Point Colors and Symbols

solution


plot(x = mtcars$wt, y = mtcars$mpg, 
     col = "red",        # Change point color to red
     pch = 17,           # Use filled triangle as plotting symbol
     main = "Weight vs MPG", 
     xlab = "Weight", 
     ylab = "Miles Per Gallon")
  • Task: Create a scatter plot of mtcars$wt against mtcars$mpg. Change the point color to red and use a different plotting symbol (e.g., a filled triangle).

  • Hint: Use the col and pch parameters in the plot() function.

Exercise 2: Adding Titles and Labels

solution


plot(x = mtcars$disp, y = mtcars$hp, 
     main = "Displacement vs Horsepower",  # Add title
     xlab = "Displacement (cu. in.)",      # Add x-axis label
     ylab = "Horsepower (hp)")             # Add y-axis label
  • Task: Create a plot of mtcars$hp against mtcars$disp. Add a title, x-axis label, and y-axis label.

  • Hint: Use the main, xlab, and ylab parameters.

Exercise 3: Modifying the Background Color of the Plot Area

solution


plot(x = mtcars$wt, y = mtcars$mpg, 
     type = "n",                # Do not plot points yet
     main = "Weight vs MPG", 
     xlab = "Weight", 
     ylab = "Miles Per Gallon")

# Change background color
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4], 
     col = "lightblue", 
     border = NA)      

# Plot points on top
points(x = mtcars$wt, y = mtcars$mpg, pch = 19)   
  • Task: Create a plot of mtcars$wt against mtcars$mpg and change the background color of the plot area to light blue.

  • Hint: Use the rect() function after creating the plot.

Exercise 4: Adding Grid Lines

solution


plot( x = mtcars$qsec, y = mtcars$drat, 
     main = "1/4 Mile Time vs Rear Axle Ratio", 
     xlab = "1/4 Mile Time (seconds)", 
     ylab = "Rear Axle Ratio")

# Add dotted gray grid lines
grid(col = "gray", lty = "dotted")        
  • Task: Create a plot of mtcars$qsec against mtcars$drat and add dotted gray grid lines to the plot.

  • Hint: Use the grid() function.

Exercise 5: Customizing Axes

solution


plot(x = mtcars$wt, y = mtcars$mpg, 
     xaxt = "n",            # Remove x axes
     yaxt = "n",            # Remove y axes  
     main = "Weight vs MPG", 
     xlab = "Weight", 
     ylab = "Miles Per Gallon")

# Custom x-axis with specific ticks
axis(1, at = seq(from = 1, to =6, by = 1),           
     labels = paste(seq(from = 1, to = 6, by = 1), "tons"))

# Custom y-axis with specific ticks
axis(2, at = seq(from = 10, to = 35, by = 5),         
     labels = paste(seq(from = 10, to =35, by = 5), "MPG"))

# Plot points on top
points(x = mtcars$wt, y = mtcars$mpg, pch = 19)   
  • Task: Create a plot of mtcars$wt against mtcars$mpg but remove the default axes. Add custom axes with different tick marks and labels.

  • Hint: Use xaxt = "n" and yaxt = "n" in plot(), then use axis() to add custom axes.

Exercise 6: Multiple Plots in a Grid Layout

solution

# Set up a 2x2 grid layout
par(mfrow = c(2, 2))

# First plot
plot(x = mtcars$wt, y = mtcars$mpg, main = "Weight vs MPG")

# Second plot
plot(x = mtcars$disp, y = mtcars$hp, 
  main = "Displacement vs Horsepower")

# Third plot
plot(x = mtcars$qsec, y = mtcars$drat, 
  main = "1/4 Mile Time vs Rear Axle Ratio")

# Fourth plot
plot(x = mtcars$wt, y = mtcars$hp, 
  main = "Weight vs Horsepower")
  • Task: Create four plots (e.g., mtcars$wt vs. mtcars$mpg, mtcars$hp vs. mtcars$disp, etc.) in a 2x2 grid layout on the same page.

  • Hint: Use par(mfrow = c(2, 2)).

Exercise 7: Custom Plot Layout

solution


layout(matrix(c(1, 2, 3, 3), nrow = 2, byrow = TRUE), 
        widths = c(1, 2), 
       heights = c(1, 2))

# First plot
plot(x = mtcars$wt, y = mtcars$mpg, main = "Weight vs MPG")

# Second plot
plot(x = mtcars$disp, y = mtcars$hp, main = "Displacement vs Horsepower")

# Third plot
plot(x = mtcars$qsec, y = mtcars$drat, main = "1/4 Mile Time vs Rear Axle Ratio")
  • Task: Create a custom layout with three plots where the first two plots are arranged side by side on the top, and the third plot spans the entire bottom row.

  • Hint: Use layout() with a custom matrix.

Exercise 8: Adding a Legend

solution


colors <- if_else(mtcars$am == 0, "red", "blue")

plot(x = mtcars$wt, y = mtcars$mpg, 
      col = colors, 
      pch = 19, 
     main = "Weight vs MPG by Transmission",
     xlab = "Weight", 
     ylab = "Miles Per Gallon")

legend("topright", 
    legend = c("Automatic", "Manual"), 
       col = c("red", "blue"), 
       pch = 19)
  • Task: Create a plot of mtcars$wt against mtcars$mpg with different colors for automatic and manual transmissions (use mtcars$am to distinguish). Add a legend to the plot.

  • Hint: Use legend() to add the legend.

Exercise 9: Adding Text Annotations

solution

plot(x = mtcars$wt, y = mtcars$mpg, 
      pch = 19, 
     main = "Weight vs MPG", 
     xlab = "Weight", 
     ylab = "Miles Per Gallon")

# Find the point with the highest MPG
max_mpg <- which.max(mtcars$mpg)

# Add text annotation
text(x = mtcars$wt[max_mpg], y = mtcars$mpg[max_mpg], 
     labels = "Highest MPG", 
        pos = 4, 
        col = "red")
  • Task: Create a scatter plot and add custom text annotations at specific points on the plot (e.g., annotate the point with the highest MPG).

  • Hint: Use the text() function.