How to display all x labels in R barplot?

前端 未结 3 1664
有刺的猬
有刺的猬 2020-11-29 02:11

This is a basic question but I am unable to find an answer. I am generating about 9 barplots within one panel and each barplot has about 12 bars. I am providing all the 12 l

相关标签:
3条回答
  • 2020-11-29 02:51

    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

    0 讨论(0)
  • 2020-11-29 03:00

    You may be able get all of the labels to appear if you use las=2 inside the plot() call. Otherwise, you will need to use xaxt="n" and then put the labels in with a separate call to axis(1, at= ..., labels=...).

    Another method is to first collect the midpoints and then use text() with xpd and srt 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.

    0 讨论(0)
  • 2020-11-29 03:02

    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
    

    Example of plot with labels rotated and small

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

    0 讨论(0)
提交回复
热议问题