Search code examples
rggplot2axis-labels

How to rotate a part of label axis with several variables in R ggplot2


I take the same example published here

So the dataframe is as follows:

results <- data.frame(Name=factor(c("Mark", "Mark", "Sue", "Sue")), 
           Tutor= factor(c("Eric", "Eric", "Richard", "Richard")),
           Test= factor(c("Maths","English","Maths", "English")),
           Score= c(100,91,88,71),
           Percent=c(100,91,100,80.7),
           school.year= c(2,2,5,5))

I have taken the first proposed solution to label an axis with several variables so :

 results$label <- paste(results$Name,results$Tutor,sep='\n')

 ggplot(results, aes(y=Percent, x=label, colour=Test, fill=Test)) +
 geom_bar(stat='identity', position='dodge') +
 ggtitle('Test Results') +
 ylab('Percent')

We obtain this graph

enter image description here

Now I would like to rotate (90°) only the first row of the x axis labels as shown in this graph:

enter image description here

Is there a way to do this? Many thanks


Solution

  • It may not be the best way, but you can use annote() from ggplot to do this. I changed the label from Tutor and Name just to Tutor and added a text-label for the Name.

    results$label <- paste(results$Tutor)
    row1 <- results$Name
    
        ggplot(results, aes(y=Percent, x=label, colour=Test, fill=Test)) +
      geom_bar(stat='identity', position='dodge') +
      ggtitle('Test Results') +
      annotate(geom = "text", x=results$label, y=-5, label=row1, size=3, angle = 90)+
      ylab('Percent')
    

    enter image description here

    Of course you can adjust the size and position of the added text label.