[This article was first published on Learning R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
[email protected] blog shows how to fill in the area between two crossing lines in an Excel chart. This post was also published as a guest-post on PTS blog.
As I am planning to colour the plot above generated using geom_ribbon the points of intersection need also to be presented in the form expected by geom_ribbon (x, ymin, ymax) – a simple copy of y3 accomplishes this.
> cross$y4 <- cross$y3
Additional error-checking is also obviously needed, as is indicated by the position of the left and rightmost green dots on the above graph – any two lines can have a point of intersection which falls outside the limits of the particular plot.
For ggplot2 to be able to vary the fill colour at each crossing of the lines it needs to know the start and end point of each coloured area. This means that the middle points of intersection need to be duplicated, as they would be part of two adjacent areas filled with different colours.