Change Axis Labels of Boxplot in R
A box graph is a chart that is used to display information in the form of distribution by drawing boxplots for each of them. Boxplots help us to visualize the distribution of the data by quartile and detect the presence of outliers. Adding axis labels for Boxplot will help the readability of the boxplot.
In this article, we will discuss how to change the axis labels of boxplot in R Programming Language.
Method 1: Using Base R
Boxplots are created in R Programming Language by using the boxplot() function.
boxplot(x, data, notch, varwidth, names, main)
- x: This parameter sets as a vector or a formula.
- data: This parameter sets the data frame.
- notch: This parameter is the label for horizontal axis.
- varwidth: This parameter is a logical value. Set as true to draw width of the box proportionate to the sample size.
- main: This parameter is the title of the chart.
- names: This parameter are the group labels that will be showed under each boxplot.
If made with basic R, we use the names parameter of the boxplot() function. For this boxplot data, has to be first initialized and the name which has to be added to axis is passed as vector. Then boxplot() is called with data and names parameter set to this vector.
This can also be done to Horizontal boxplots very easily. To convert this to horizontal boxplot add parameter Horizontal=True and rest of the task remains the same. For this, labels will appear on y-axis.
Method 2: Using ggplot2
If made with ggplot2, we change the label data in our dataset itself before drawing the boxplot.
Reshape module is used to convert sample data from wide format to long format and ggplot2 will be used to draw boxplot. After data is created, convert data from wide format to long format using melt function. Now, change the variable name in the dataset and simply draw the boxplot.
This can be done to Horizontal boxplots very easily. To convert this to Horizontal Boxplot add coord_flip() in the boxplot code, and rest remains the same as above.
geom_boxplot() + coord_flip()