How can I manipulate a ggplot in R to allow extra room on lhs for angle=45 long x-axis labels?

17,703

Solution 1

There would be a better solution to your problem: Just follow the link user3055034 provided. Tweak plot.margin with the new margin() in analogy to my example below.

library(ggplot2)

# long labels
labels <- c(paste(c(letters, letters), collapse = ""), "6", "8")

ggplot(mtcars, aes(as.factor(cyl), mpg)) +
  geom_point() +
  scale_x_discrete(labels = labels) +
  theme(axis.text.x = element_text(angle = 45, size = 9,
        color = "black", face = "plain", vjust = 1, hjust = 1),
        plot.margin = margin(10, 10, 10, 100))

Solution 2

This is probably not the best answer, but I added several "\n\n\n" before my y-axis label text which made the label text wider. This moves the actual plot and its associated labels farther to the right, giving more room for the text on the left.

ggplot(aes(x = cm, y = ahead_aadt),
        data = sbt) + 
   geom_point( ) + geom_line() +
   ggtitle("Ahead AADT Traffic Counts On US 101 in S Santa Barbara Cty") + 
   theme(axis.text.x = element_text(angle=45, size = 9,
     color = "black", face = "plain", vjust = 1, hjust = 1), 
     panel.grid.major.x = element_line(colour = "black", linetype = "dotted")) +
  xlab("Cumulative Mileage") + ylab("\n\n\nAhead AADT") +
   scale_x_continuous(breaks = sbt$cm,
                      labels =  sbt$description)
Share:
17,703
Susan
Author by

Susan

Updated on July 24, 2022

Comments

  • Susan
    Susan almost 2 years

    I have several geom_bar ggplots where I have long names for x-axis text. If I plot them at angle=90, it takes a lot of room at the bottom of the graph, so I am trying angle=45. This causes the left hand side of the first label to be cut off. Is there a way to increase the left margin?

    (not allowed to post an image example)

    ggplot(aes(x = cm, y = ahead_aadt),
            data = sbt) + 
       geom_point( ) + geom_line() +
       ggtitle("Ahead AADT Traffic Counts On US 101 in S Santa Barbara Cty") + 
       theme(axis.text.x = element_text(angle=45, size = 9,
         color = "black", face = "plain", vjust = 1, hjust = 1), 
         panel.grid.major.x = element_line(colour = "black", linetype = "dotted")) +
      xlab("Cumulative Mileage") + ylab("Ahead AADT") +
       scale_x_continuous(breaks = sbt$cm,
                          labels =  sbt$description)
    
    • user3055034
      user3055034 over 8 years
      Please see the answer here
    • Shawn Mehan
      Shawn Mehan over 8 years
      can you give us a dput() with some data?
  • Susan
    Susan over 8 years
    Thank you! I somehow didn't see plot.margin when I was looking for help.