[r] Rotating x axis labels in R for barplot

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)/average) * 100,
        srt       = 45,
        adj       = 1,
        xpd       = TRUE,
        names.arg = data1[,2],
        col       = c("#3CA0D0"),
        main      = "Best Lift Time to Vertical Drop Ratios of North American Resorts",
        ylab      = "Normalized Difference",
        yaxt      = 'n',
        cex.names = 0.65,
        cex.lab   = 0.65)

This question is related to r graph plot bar-chart axis-labels

The answer is


In the documentation of Bar Plots we can read about the additional parameters (...) which can be passed to the function call:

...    arguments to be passed to/from other methods. For the default method these can 
       include further arguments (such as axes, asp and main) and graphical 
       parameters (see par) which are passed to plot.window(), title() and axis.

In the documentation of graphical parameters (documentation of par) we can see:

las
    numeric in {0,1,2,3}; the style of axis labels.

    0:
      always parallel to the axis [default],

    1:
      always horizontal,

    2:
      always perpendicular to the axis,

    3:
      always vertical.

    Also supported by mtext. Note that string/character rotation via argument srt to par does not affect the axis labels.

That is why passing las=2 is the right answer.


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


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.


You may use

par(las=2) # make label text perpendicular to axis

It is written here: http://www.statmethods.net/graphs/bar.html


use optional parameter las=2 .

barplot(mytable,main="Car makes",ylab="Freqency",xlab="make",las=2)

enter image description here


You can use ggplot2 to rotate the x-axis label adding an additional layer

theme(axis.text.x = element_text(angle = 90, hjust = 1))

You can simply pass your data frame into the following function:

rotate_x <- function(data, column_to_plot, labels_vec, rot_angle) {
    plt <- barplot(data[[column_to_plot]], col='steelblue', xaxt="n")
    text(plt, par("usr")[3], labels = labels_vec, srt = rot_angle, adj = c(1.1,1.1), xpd = TRUE, cex=0.6) 
}

Usage:

rotate_x(mtcars, 'mpg', row.names(mtcars), 45)

enter image description here

You can change the rotation angle of the labels as needed.


Examples related to r

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R? R : how to simply repeat a command? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium How to show code but hide output in RMarkdown? remove kernel on jupyter notebook Function to calculate R2 (R-squared) in R Center Plot title in ggplot2 R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph R multiple conditions in if statement What does "The following object is masked from 'package:xxx'" mean?

Examples related to graph

How to plot multiple functions on the same figure, in Matplotlib? Python equivalent to 'hold on' in Matlab How to combine 2 plots (ggplot) into one plot? how to draw directed graphs using networkx in python? What is the difference between dynamic programming and greedy approach? Plotting using a CSV file Python equivalent of D3.js Count number of times a date occurs and make a graph out of it How do I create a chart with multiple series using different X values for each series? Rotating x axis labels in R for barplot

Examples related to plot

Fine control over the font size in Seaborn plots for academic papers Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python Modify the legend of pandas bar plot Format y axis as percent Simple line plots using seaborn Plot bar graph from Pandas DataFrame Plotting multiple lines, in different colors, with pandas dataframe Plotting in a non-blocking way with Matplotlib What does the error "arguments imply differing number of rows: x, y" mean? matplotlib get ylim values

Examples related to bar-chart

matplotlib: plot multiple columns of pandas data frame on the bar chart R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph How to display the value of the bar on each bar with pyplot.barh()? How can I change the Y-axis figures into percentages in a barplot? How to get a barplot with several variables side by side grouped by a factor Stacked Bar Plot in R Setting Different Bar color in matplotlib Python Grouped bar plot in ggplot Simplest way to do grouped barplot R barplot Y-axis scale too short

Examples related to axis-labels

Python: How to increase/reduce the fontsize of x and y tick labels? Rotating x axis labels in R for barplot Remove plot axis values