R: How to Change X-Axis Labels of Barplot


You can use one of the following methods to change the x-axis labels of a barplot in R:

Method 1: Use Values from Column as X-Axis Labels

#create barplot and use values from 'team' column as x-axis labels
barplot(height=df$points, names=df$team)

In this particular example we use the names argument to specify a column from the data frame to use as the x-axis labels.

Method 2: Specify Custom Values to Use as X-Axis Labels

#create barplot with custom x-axis labels
barplot(height=df$points, names.arg=c('A', 'B', 'C', 'D', 'E'))

In this particular example we use the names.arg argument to specify a vector of values to use as the x-axis labels.

The following examples show how to use each method in practice with the following data frame in R:

#create data frame
df<- data.frame(team=c('Mavs', 'Nets', 'Kings', 'Hawks', 'Heat'),
                points=c(22, 24, 10, 31, 15))

#view data frame
df

   team points
1  Mavs     22
2  Nets     24
3 Kings     10
4 Hawks     31
5  Heat     15

Example 1: Use Values from Column as X-Axis Labels

We can use the following code to create a barplot in R and use the values from the team column in the data frame as the x-axis labels:

#create barplot and use values from 'team' column as x-axis labels
barplot(height=df$points, names=df$team)

Notice that the x-axis labels correspond to the values from the team column in the data frame.

Example 2: Specify Custom Values to Use as X-Axis Labels

We can use the following code to create a barplot in R and use the names.arg argument to specify custom values to use for the x-axis labels:

#create barplot with custom x-axis labels
barplot(height=df$points, names.arg=c('A', 'B', 'C', 'D', 'E'))

R barplot change x-axis labels

Notice that the x-axis labels correspond to the values that we specified using the names.arg argument.

Additional Resources

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

How to Create a Grouped Barplot in R
How to Create a Stacked Barplot in R
How to Create a Barplot in ggplot2 with Multiple Variables

Leave a Reply

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