The box function

The R box function allows adding a box around plots. This is particularly useful when you add a new axis with the axis function and want to draw the box again. You can also customize the color, the line type, the line width and even the type of the box.

Example 1. Adding a blue box to the plot. Note that we set axes = FALSE to avoid displaying the default box and axes.

# Plot without axes
curve(cos, -10, 10, axes = FALSE)

# Blue dashed box
box(col = 4, lty = 2)

Adding a box in R with box function

Example 2. Adding a box after modifying the axes with the axis function.

# Plot without axes
curve(cos, -10, 10, axes = FALSE)

# Custom axis
axis(1, at = c(-2 * pi, pi, -pi, 0, 2 * pi),
     labels = expression(-2 * pi, -pi, 0,
                         pi, 2 * pi))

axis(2, lwd = 2, lty = 2)

# Box with wide line
box(lwd = 2)

box function in R

Example 3. Adding a box to the whole plot.

# Plot without axes
curve(cos, -10, 10)

# Border box
box("figure", col = 4, lwd = 4)

Adding a box around the whole plot in R

Box type with bty argument

By default, base R plots have a box around them. This box can be customized with the bty argument of the corresponding function. If the plotting function does not support this argument (like boxplot) you can set it inside par function.

Full box in R with bty argument

Full box: bty = "o" (Default)

curve(cos, -10, 10,
      bty = "o")

Left-bottom box in R

Left and bottom: bty = "L"

curve(cos, -10, 10,
      bty = "L")

Bottom-left-top box in R

Top, left and bottom: bty = "C"

curve(cos, -10, 10,
      bty = "C")

Top-right box in R

Top and right: bty = "7"

curve(cos, -10, 10,
      bty = "7")

Top-right-bottom box in R

Top, right and bottom: bty = "]"

curve(cos, -10, 10,
      bty = "]")

Left-bottom-right box in R

Left, bottom and right: bty = "U"

curve(cos, -10, 10,
      bty = "U")

Remove box in R

No box: bty = "n"

curve(cos, -10, 10,
      bty = "n")

The bty argument can also be used within the box function, which allows customizing the color, the type and the width of the box.

Customize the box of the plot in R

curve(cos, -10, 10,
      axes = FALSE)

box(col = 2, bty = "U", lty = 2, lwd = 2)

As we pointed out before, with some functions you will need to specify the argument inside the par function. As an example, if you want to draw a box plot without a box you can type:

Remove the box of boxplot in R

par(bty = "n")

# Data
set.seed(1)
x <- rnorm(50)

# Plot
boxplot(x)

Note that "o", "7", "]", "L" and "U" represent the sides of the box that are actually drawn. This is a good way to remember them. You can also set the letters in lower case instead of in upper case.

See also