R: Rotate x-axis labels in a barplot

1

I wanted to know how to tilt (certain degrees to the right) the axis labels x of a barplot . When I run the script of barplot :

     barplot(Indexpercentage, horiz = FALSE, col = c("Green","Orange","Red","Blue"), beside = FALSE, xlim=c(0,5),ylab ="Diversity (%)", xlab="Diversity measure",font.axis=2, cex.axis = 0.8,cex.names = 0.8,font.lab=2,yaxp = c(0, 100,4))

I get this plot , from which the labels of the second and fourth columns can not be read (I suppose that they overlapped)

I would also like to know if there is any way to show the axis line x below barplot .

Thanks in advance.

    
asked by Adrián P.L. 20.12.2017 в 17:39
source

1 answer

1

If the problem of X-axis labels has to do with overlapping, you can do two things:

  • Enlarge the graphic: Simply expanding the Rstudio plot window, or clicking on the zoom button.
  • Show the labels vertically using the las=2 parameter together with the function axis()
  • Let's see an example:

    counts <- table(mtcars$vs, mtcars$gear)
    colnames(counts) <- c("Etiqueta 1", "Etiqueta 2", "Etiqueta 3")
    barplot(counts, main="Car Distribution by Gears and VS",
            col=c("darkblue","red"),
            legend = rownames(counts))
    

    One way is using the las=2 parameter as follows:

    barplot(counts, main="Car Distribution by Gears and VS",
            col=c("darkblue","red"),
            legend = rownames(counts), las=2)
    

    If you also want an X axis, you can use axis() :

    barplot(counts, main="Car Distribution by Gears and VS",
            col=c("darkblue","red"),
            legend = rownames(counts),
            names.arg = c(NA, NA, NA),
            ) + axis(1, at=seq(1,3),labels=colnames(counts), las=2)
    

    And if you eventually want the labels with some inclination:

    x <- barplot(counts, 
            main="Car Distribution by Gears and VS",
            col=c("darkblue","red"),
            xaxt="n")
    
    text(cex=1, x=x, y=-1.25, colnames(counts), xpd=TRUE, srt=45, pos=2)
    

        
    answered by 20.12.2017 / 20:03
    source