Table of Contents
In R, the X-axis labels of a barplot can be changed by utilizing the “xlab” argument in the “barplot” function. This allows users to specify the desired labels for the X-axis, which can be either numerical or categorical. By providing a vector of labels as the argument, the X-axis labels can be easily customized to accurately represent the data being displayed on the barplot. This feature allows for greater flexibility and clarity in presenting data in a barplot format.
R: 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'))
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: