Adding second line of X-axis labels

1,473 views
Skip to first unread message

Jennifer Thompson

unread,
Mar 21, 2011, 5:23:46 PM3/21/11
to ggplot2
I'm looking for a way to add an additional line of text to X axis
labels, but in different spots than the first line of text. For
example, in the following test code...

testdata <- data.frame(var1 = 1:10, var2 = 1:10)
ggplot(data = testdata, mapping = aes(x = var1, y = var2)) +
geom_line() +
scale_x_continuous(limits = c(1, 10), breaks = c(1, 2, 4, 5, 7, 8,
10), labels = c('A\n1', 'B\n2', 'C\n3', 'D\n4', 'E\n5', 'F\n6', 'G'))

I'd like to shift the numbers over, such that 1 is midway between A
and B, 2 is between B and C, etc. I can "fake it" using "\n" and
additional breaks, but this gives me more tick marks and white
dividing lines, neither of which I want. (I.e., I want the distance
between the thicker white lines at A and B to be different than the
distance between those lines at B and C.)

Is there any way this is possible? I've tried using annotate() and
geom_text(), but haven't had much luck so far. Thank you in advance!

Dennis Murphy

unread,
Mar 21, 2011, 7:31:29 PM3/21/11
to Jennifer Thompson, ggplot2
Hi:

It's a kludge, but try this:


ggplot(data = testdata, mapping = aes(x = var1, y = var2)) +
 scale_x_continuous(limits = c(1, 10),
      breaks = c(1, 1.5, 2, 3, 4, 4.5, 5, 6, 7, 7.5, 8, 9, 10),
      labels = c('A', '\n1', 'B', '\n2', 'C', '\n3', 'D', '\n4',
                 'E', '\n5', 'F', '\n6', 'G')) +
      opts(panel.grid.major = theme_blank(), panel.grid.minor = theme_blank()) +
      geom_vline(xintercept = c(1, 2, 4, 5, 7, 8, 10), colour = 'white') +
      geom_hline(yintercept = c(2, 4, 6, 8, 10), colour = 'white') +
      geom_line()  + opts(axis.ticks = theme_blank())

HTH,
Dennis


--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: http://gist.github.com/270442

To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+u...@googlegroups.com
More options: http://groups.google.com/group/ggplot2

Jennifer Thompson

unread,
Mar 21, 2011, 10:08:42 PM3/21/11
to ggp...@googlegroups.com, Dennis Murphy
Dennis, thank you so much! I don't mind a kludge at all, as long as it works. :) That works great! There's so much to learn about this package - that will help me out a lot in the future, I'm sure.
Reply all
Reply to author
Forward
0 new messages