Rotating x axis labels in R for barplot

后端 未结 8 612
暖寄归人
暖寄归人 2020-11-27 12:29

I am trying to get the x axis labels to be rotated 45 degrees on a barplot with no luck. This is the code I have below:

barplot(((data1[,1] - average)/averag         


        
相关标签:
8条回答
  • 2020-11-27 12:57

    Andre Silva's answer works great for me, with one caveat in the "barplot" line:

    barplot(mtcars$qsec, col="grey50", 
        main="",
        ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
        xlab = "",
        xaxt = "n", 
        space=1)
    

    Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.

    0 讨论(0)
  • 2020-11-27 13:00

    Rotate the x axis labels with angle equal or smaller than 90 degrees using base graphics. Code adapted from the R FAQ:

    par(mar = c(7, 4, 2, 2) + 0.2) #add room for the rotated labels
    
    #use mtcars dataset to produce a barplot with qsec colum information
    mtcars = mtcars[with(mtcars, order(-qsec)), ] #order mtcars data set by column "qsec"
    
    end_point = 0.5 + nrow(mtcars) + nrow(mtcars) - 1 #this is the line which does the trick (together with barplot "space = 1" parameter)
    
    barplot(mtcars$qsec, col = "grey50", 
            main = "",
            ylab = "mtcars - qsec", ylim = c(0,5 + max(mtcars$qsec)),
            xlab = "",
            space = 1)
    #rotate 60 degrees (srt = 60)
    text(seq(1.5, end_point, by = 2), par("usr")[3]-0.25, 
         srt = 60, adj = 1, xpd = TRUE,
         labels = paste(rownames(mtcars)), cex = 0.65)
    

    enter image description here

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