How to display all x labels in R barplot?

R won't label every bar if the labels are too big.

I would suggest trying to rotate the labels vertically by passing in the las=2 argument to your plotting function.

If the labels are still too large, you can try shrinking the font by using the cex.names=.5 argument.

Sample Data for plot

sample_curve <- c(2.31,2.34,2.37,2.52,2.69,2.81,2.83,2.85,2.94, 3.03,  3.21,  3.33)   # create a sample curve
names(sample_curve)<-c("1 MO","2 MO","3 MO","6 MO","1 YR","2 YR","3 YR","5 YR","7 YR","10 YR","20 YR","30 YR") # label the curve

Example of plot with labels too big

barplot(sample_curve) # labels too big for the plot

labels too big

Example of plot with labels rotated and small

barplot(sample_curve, las=2, cex.names=.5) # lables are rotated and smaller, so they fit

rotated and smaller


You may be able get all of the labels to appear if you use las=2 inside the plot() call. This argument and the others mentioned below are described in ?par which sets the graphical parameters for plotting devices. That rotates the text 90 degrees. Otherwise, you will need to use xaxt="n" (to suppress ticks and labels) and then put the labels in with a separate call to axis(1, at= <some numerical vector>, labels=<some character vector>).

#  midpts <- barplot( ... ) # assign result to named object
axis(1, at = midpts, labels=names(DD), cex.axis=0.7) # shrinks axis labels

Another method is to first collect the midpoints and then use text() with xpd=TRUE to allow text to appear outside the plot area and srt be some angle for text rotation as named arguments to control the degree of text rotation:

text(x=midpts, y=-2, names(DD), cex=0.8, srt=45, xpd=TRUE)

The y-value needs to be chosen using the coordinates in the plotted area.

Copying a useful comment: For future readers who don't know what these arguments do: las=2 rotates the labels counterclockwise by 90 degrees. furthermore, if you need to reduce the font you can use cex.names=.5 to shrink the size down


To get rotated labels on a base R barplot, you could (like I do here) adapt one of the examples given in the vignette of the gridBase package:

library(grid)
library(gridBase)

## Make some data with names long enough that barplot won't print them all
DD <- table(rpois(100, lambda=5))
names(DD) <- paste("long", names(DD), sep="_")

## Plot, but suppress the labels
midpts <- barplot(DD, col=rainbow(20), names.arg="")

## Use grid to add the labels    
vps <- baseViewports()
pushViewport(vps$inner, vps$figure, vps$plot)

grid.text(names(DD),
    x = unit(midpts, "native"), y=unit(-1, "lines"),
    just="right", rot=50)

popViewport(3)

enter image description here

Tags:

Graph

R