Rotation and justification of axis texts in ggplot2


When axis texts are long, usually the texts are rotated to avoid overlap.
ggplot2 can well handle the rotation of axis texts and justification.

Here is examples.

Data and a basic layer:

test.dat <- data.frame(
  desc=c("A very long name", "Another very long name"),
  value=c(2,3))
p <- qplot(x=desc, y=desc, data=test.dat)

 

Example 1:

p + opts(axis.text.y=theme_text(hjust=0, angle=0), axis.text.x = theme_text(hjust=0, angle=90))


 

Example 2:

p + opts(axis.text.y=theme_text(hjust=1, angle=0), axis.text.x = theme_text(hjust=1, angle=90))

 

Example 3:

p + opts(axis.text.y=theme_text(hjust=0, angle=180), axis.text.x = theme_text(hjust=0, angle=270))

 

Example 4:

p + opts(axis.text.y=theme_text(hjust=1, angle=180), axis.text.x = theme_text(hjust=1, angle=270))

 

Unfortunately, the combination of oblique rotation and justification is hard to work well.

6 thoughts on “Rotation and justification of axis texts in ggplot2

    • Here is an example:

      library(ggplot2)
      d <- data.frame(x = c("abc", "def", "ghi", "xyz"), y = 1:4)
      ggplot(d, aes(x, y)) + geom_point() +
      theme(axis.text.x = element_text(angle = c(90, 0, 0, 90)))

      • On my fedora 19 there is a message but the picture is correct:

        —————————————————————————-
        Warning message:
        In if (angle == 90) { :
        the condition has length > 1 and only the first element will be used
        —————————————————————————-

        ===========================
        I have done the following before:
        —————————————————————————-
        p0 <- ggplot(selection,aes(x=xscale,y=protok))
        #p0 <- ggplot(selection,aes(x=xlabele,y=protok))
        p1 kut
        [1] 90 0 0 0 0 0 90

        and xlabele:
        > xlabele
        [1] “10.3.1985” “1986” “1987” “1988” “22.6.1988”
        —————————————————————————-
        but only the first label is rotated.

  1. Sorry. Again:
    p0 <- ggplot(selection,aes(x=xscale,y=protok)) + geom_line(color = "darkblue",fill = "lightblue",stat="identity") +
    scale_x_continuous(breaks=xbreaks, labels=xlabele) + theme(axis.text.x = element_text(angle = kut))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s