Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add a secondary y axis to ggplot2 plots - make it perfect

Tags:

plot

r

ggplot2

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)))
like image 792
jianfeng.mao Avatar asked Feb 01 '12 13:02

jianfeng.mao


People also ask

How do I get 2 y axis in ggplot2?

ggplot2 dual axes supportscale_x_continuous() and scale_y_continuous() can now display a secondary axis that is a one-to-one transformation of the primary axis (e.g. degrees Celcius to degrees Fahrenheit). The secondary axis will be positioned opposite to the primary axis and can be controlled with the sec.

How do I customize the y axis in R?

To change the axis scales on a plot in base R Language, we can use the xlim() and ylim() functions. The xlim() and ylim() functions are convenience functions that set the limit of the x-axis and y-axis respectively.

How do I add a second Y axis in R?

Example: Create Plot with 2 Axes in R Let's deconstruct the code: par(mar = c(5, 4, 4, 4) + 0.3) – This code defines how much white space should be shown around the plot. It is important to leave enough space for the second y-axis. plot(x, y1, pch = 16, col = 2) – This code creates the first plot (i.e. the red dots).


1 Answers

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

like image 186
Geek On Acid Avatar answered Oct 23 '22 01:10

Geek On Acid