13

Adding a secondary y axis, scaled one of the original y axis. This topic is not new. It has been touched times, for example on this ggplot2 google groups thread. Following Hadley's advice, I tried to add the secondary y axis by geom_vline, geom_segment, and geom_text. But, it is still ugly.

So I would ask for your help on making it perfect. I think many ggplot2 users would be interested in this topic and prefer any your expertise or contributions. Thanks in advance.

#########################################
# what I have gotten.
library(ggplot2)

# build up a box plot
p <- ggplot(mtcars, aes(factor(cyl), mpg)) 

# add the secondary y axis on right side of the plot
p + geom_boxplot() + geom_vline(xintercept = 3.5) + 
 geom_segment(aes(x=3.49, y=c(7,14,21,28), xend = 3.52, yend = c(7,14,21,28))) +
 geom_text(aes(x=3.55, y=c(7,14,21,28), label=c(7,14,21,28)))
BarkleyBG
  • 664
  • 5
  • 16
jianfeng.mao
  • 945
  • 3
  • 13
  • 21
  • Generally it is not advisable to use secodary y-axis... – jrara Feb 01 '12 at 14:05
  • 1
    Sorry what I want is in fact not a secondary y-axis, it is just a label. This label is necessary, sometimes. – jianfeng.mao Feb 01 '12 at 14:57
  • You might wish to edit your question to reflect the fact you wish an extra label. I just asked a similar question, but specific to faceting context: http://stackoverflow.com/questions/11353287/how-do-you-add-a-general-label-to-facets-in-ggplot2 – Etienne Low-Décarie Jul 05 '12 at 22:26
  • Somewhat related, I'd love to be able to position the primary axis on the right side of a chart. For time series in particular, it is often the case that you are most interested in being able to readily read off the most recent data values rather than the oldest. – seancarmody Aug 12 '12 at 12:51
  • @jrara Sais who? In scientific publications and journals, secondary axis plots are common place. – Nicholas Hamilton Feb 13 '13 at 21:33
  • @ADP Sorry for being imprecise, I meant it is not advisable to use secondary y-axis with secondary scale. – jrara Feb 14 '13 at 05:18

1 Answers1

2

To avoid hacking, you might use facet_grid instead. Depending on your data, you can customize it pretty well, to make it into more general secondary axis.

 library(ggplot2)
 ggplot(mtcars, aes(factor(cyl), mpg)) + 
   geom_boxplot() + 
   facet_grid(cyl ~., scales = "free")

enter image description here

Geek On Acid
  • 6,330
  • 4
  • 44
  • 64
  • 1
    Thanks a lot, Dear Geek On Acid. That is an options. But, it is not what I want. In my real case, I have more than 50 levels of x-axis. It is very difficult for our eyes to see a plot with >50 facets. – jianfeng.mao Feb 01 '12 at 16:00