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)))
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.
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.
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).
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With