How to Use the box() Function in R


Often you may want to draw a box around a plot created in base R.

The easiest way to do so is by using the box() function from base R, which is designed to perform this exact task.

The box() function uses the following basic syntax:

box(which = “plot”, lty = “solid”, …)

where:

  • which: character, one of “plot”, “figure”, “inner” and “outer”
  • lty: The line type to use for the plot

Note that the box() function draws a solid black box around the plot by default, but you can use the lty argument along with any other arguments from base R to customize the appearance of the plot.

The following example shows how to use the box() function in practice in several different scenarios.

Note: The box() function comes built-in with base R so you do not need to install or load any external packages to use this function.

Example: How to Use the box() Function in R

Suppose that we define two vectors, x and y:

#create x and y vectors
x <- c(1, 2, 3, 4, 5)
y <- c(1, 4, 9, 15, 22)

We can use the plot() function from base R to create a scatterplot of the points in these two vectors:

#create scatterplot of x vs. y
plot(x, y, col='blue', pch=19)

This produces the following scatterplot:

Note: We used the col argument to specify the color of the points in the plot and we used the pch argument with a value of 19 to specify that the points should be filled-in circles in the plot.

By default, plots in base R have a black box around them.

However, you can use the box() function to customize the appearance of the box around the plot.

For example, we could use the following syntax with the box() function to create a red box around the plot:

#create scatterplot of x vs. y
plot(x, y, col='blue', pch=19)

#add box around plot
box(col='red')

This produces the following result:

Notice that a red box now appears around the outside of the plot, just as we specified.

It’s important to note that the default black box that comes with the plot() function is still under the box that we just added.

Thus, if we would like to customize the pattern of the box using lty then we need to specify axes=FALSE to turn off the underlying axes.

For example, we can use the following syntax to add a red box with dashed lines around the plot:

#create scatterplot of x vs. y
plot(x, y, col='blue', pch=19, axes=FALSE)

#add box around plot
box(col='red', lty='dashed')

This produces the following result:

Notice that a red box with dashes lines now appears around the plot.

Feel free to specify whatever values you would like for the col and lty arguments of the box() function.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Add Points to an Existing Plot in R
How to Add Text Outside of a Plot in R
How to Create an Empty Plot in R
How to Change Axis Labels of Boxplot in R

Leave a Reply

Your email address will not be published. Required fields are marked *