Add Color to Region Between Two Lines in ggplot2 Line Plot in R (2 Examples)
This article explains how to highlight the region between two ggplot2 lines with color in R.
The post consists of these content blocks:
So now the part you have been waiting for – the examples!
Example Data, Packages & Default Graphic
The following data is used as a basis for this R tutorial:
data <- data.frame(x = 1:5, # Create example data frame y1 = c(1, 3, 1, 4, 4), y2 = c(5, 4, 4, 5, 7)) data # Print example data frame
Table 1 shows the structure of the example data – It is constituted of five rows and three columns.
In this tutorial, we’ll also need to install and load the ggplot2 package.
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 package
Now, we can draw our data as shown below:
ggp <- ggplot(data, aes(x = x)) + # Create default ggplot2 line plot geom_line(aes(y = y1)) + geom_line(aes(y = y2)) ggp # Draw default ggplot2 line plot
As illustrated in Figure 1, we have plotted a ggplot2 line plot by running the previous code.
Example 1: Add Color Between Two Lines in ggplot2 Line Plot
This example explains how to fill the area between two ggplot2 lines.
For this task, we can use the R programming syntax below:
ggp + # Add color between lines geom_ribbon(aes(x = x, ymin = y1, ymax = y2), fill = "#1b98e0")
As shown in Figure 2, we have managed to create a ggplot2 line graph with blue color between the lines with the previous R programming code.
Example 2: Add Shading Between Two Lines in ggplot2 Line Plot
In Example 2, I’ll show how to draw a transparent gray shade between the lines of a ggplot2 graphic.
ggp + # Add shading between lines geom_ribbon(aes(x = x, ymin = y1, ymax = y2), fill = "gray", alpha = 0.4)
After running the previous R code the shaded region between our two lines visualized in Figure 3 has been drawn.
Video & Further Resources
Do you need more explanations on the R codes of the present article? Then I recommend watching the following video on my YouTube channel. In the video, I’m explaining the R code of this article.
Furthermore, you may have a look at some of the related R tutorials on https://statisticsglobe.com/. I have published several tutorials on topics such as text elements, colors, ggplot2, and graphics in R.
- Add Table to ggplot2 Plot
- Change Fill and Border Color of ggplot2 Plot
- Beginner/Advanced Tutorial for the ggplot2 Package
- Add Text to ggplot2 Plot in R
- Add Bold & Italic Text to ggplot2 Plot in R
- Graphics Overview in R
- Introduction to R Programming
Summary: In this tutorial, I have shown how to draw color between two lines in a ggplot2 plot in R programming. Please let me know in the comments below, if you have any additional questions. Furthermore, please subscribe to my email newsletter in order to receive regular updates on new articles.