How to Use xaxp() to Change Tick Mark Spacing in R

Often you may want to change the spacing of tick marks on the axis of a plot in R.

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

The xaxp() function uses the following basic syntax:

plot(…, xaxp = c(x1, x2, n))

where:

• x1: Minimum value on x-axis
• x2: Maximum value on x-axis
• n: Number of total tick marks

Note that you may need to play around with the value that you provide for the n argument to increase or decrease the number of tick marks and thus the spacing between the total marks.

Note that n+1 will be the total number of tick marks drawn.

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

Note: The xaxp() 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 xaxp() Function in R

First, we will create the following data frame in R that contains 100 observations with measurements on one variable named x and another variable named y:

```#make this example reproducible
set.seed(1)

#create data frame
df <- data.frame(x=runif(100, 0, 50),
y=runif(100, 0, 10))

x        y
1 13.27543 6.547239
2 18.60619 3.531973
3 28.64267 2.702601
4 45.41039 9.926841
5 10.08410 6.334933
6 44.91948 2.132081```

Note that we used the runif() function in R to generate random values from a uniform distribution, using the following basic syntax:

runif(n, min, max)

where:

• n: Number of values to generate from uniform distribution
• min: Minimum value of uniform distribution
• max: Maximum value of uniform distribution

For the x variable, we specified that it should have a range between 0 and 50.

For the y variable, we specified that it should have a range between 0 and 10.

Suppose we use the following syntax to create a scatterplot to visualize the 100 observations in this dataset:

```#create scatterplot of x vs y
plot(df\$x, df\$y, col='blue', pch=19)
```

This produces the following plot:

Note: We used pch=19 to specify that the markers in the plot should be filled-in circles.

Notice that the x-axis currently has six total tick marks.

Suppose that we would instead like to increase the spacing between the tick marks by only using five total tick marks.

We can use the following syntax with axp to do so:

```#create scatterplot of x vs y
plot(df\$x, df\$y, col='blue', pch=19, xaxp=c(x1=0, x2=50, n=4))
```

This produces the following plot:

Notice that the x-axis now has five total tick marks.

Since we specified n=4 in the xaxpt argument, we specified that we wanted n+1 = 4+1 = 5 total tick marks along the x-axis.

Feel free to increase or decrease the number for n within the xaxp argument to change the total number of tick marks and thus the spacing between the tick marks.