How to Add Vertical Lines By a Variable in Multiple Density Plots with ggplot2 in R
Last Updated :
24 Oct, 2021
In this article, we will discuss how to add vertical lines by a variable in multiple density plots with ggplot2 package in the R Programming language.
To do so first we will create multiple density plots colored by group and then add the line as a separate element.
Basic Multiple Density Plot:
To make multiple density plots with coloring by variable in R with ggplot2, we firstly make a data frame with values and category. Then we draw the ggplot2 density plot using the geom_desnity() function. To color them according to the variable we add the fill property as a category in the ggplot() function.
Syntax:
ggplot(dataFrame, aes( x, color, fill)) + geom_density()
Example:
We get multiple density plots in the ggplot of two colors corresponding to two-level/values for the second categorical variable. If our categorical variable has n levels, then ggplot2 would make multiple density plots with n densities/color.
R
# load library
library(tidyverse)
set.seed(1234)
# create the dataframe
df <- data.frame(
category=factor(rep(c("category1", "category2","category3"),
each=1000)),
value=round(c(rnorm(1000, mean=65, sd=5),
rnorm(1000, mean=85, sd=5),
rnorm(1000, mean=105, sd=5))))
# Basic density plot with custom color
# color property to determine the color of plot
# fill property to determine the color beneath plot
ggplot(df, aes(x=value, color=category, fill=category)) +
geom_density(alpha=0.3)
Output:

Adding Line by a variable
To add a line by a variable to plot create a new data frame median to a data frame that stores the median of values grouped by categories. Then use the geom_vline function to draw a line across that point colored by category of data.
Syntax:
plot + geom_vline( dataframe, aes( xintercept, color ), size)
Example:
Here, we have calculated the median of values grouped by category and stored it in a data frame named median. Then used geom_vline() function to draw a line across the plot at that point colored according to the category of data.
To create a Median data frame we use,
median <- df %>%
group_by(category) %>%
summarize(median=median(value))
Median data frame made from group_by and summarize function looks like:
# A tibble: 3 x 2
category median
<fct> <dbl>
1 category1 65
2 category2 85
3 category3 105
R
# load library
library(tidyverse)
set.seed(1234)
df <- data.frame(
category=factor(rep(c("category1", "category2","category3"),
each=1000)),
value=round(c(rnorm(1000, mean=65, sd=5),
rnorm(1000, mean=85, sd=5),
rnorm(1000, mean=105, sd=5))))
# create median data using above dataframe
# group_by function groups the data of same category
# summarize function with median
# argument calculates the median of value column
median <- df %>%
group_by(category) %>%
summarize(median=median(value))
# Basic density plot with custom color
# color property to determine the color of plot
# fill property to determine the color beneath plot
# geom_vline function draws the line across median
# of each group
ggplot(df, aes(x=value, color=category, fill=category)) +
geom_density(alpha=0.3)+
geom_vline(data = median, aes(xintercept = median,
color = category), size=0.5)
Output:
Similar Reads
Multiple Density Plots and Coloring by Variable with ggplot2 in R In this article, we will discuss how to make multiple density plots with coloring by variable in R Programming Language. To make multiple density plots with coloring by variable in R with ggplot2, we first make a data frame with values and categories. Then we draw the ggplot2 density plot using the
3 min read
How to create a plot using ggplot2 with Multiple Lines in R ? In this article, we will discuss how to create a plot using ggplot2 with multiple lines in the R programming language. Method 1: Using geom_line() function In this approach to create a ggplot with multiple lines, the user need to first install and import the ggplot2 package in the R console and then
3 min read
Adding Legend to Multiple Line Plots with ggplot in R In this article, we are going to see how can we add a legend to multiple line plots with ggplot in the R programming language. For a plot that contains more than one line plot, a legend is created by default if the col attribute is used. All the changes made in the appearance of the line plots will
2 min read
Add Vertical and Horizontal Lines to ggplot2 Plot in R In this article, we will see how to add Vertical and Horizontal lines to the plot using ggplot2 in R Programming Language. Adding Vertical Line To R Plot using geom_vline() For adding the Vertical line to the R plot, geom_vline() draws a vertical line at a specified position. Syntax: geom_vline(xint
4 min read
How To Make Density Plots with ggplot2 in R? Density plots are a data visualization method used to estimate the probability density function (PDF) of a continuous variable. They provide smooth, continuous data distribution which makes them more informative than histograms in certain situations. The plot is produced by applying a kernel functio
2 min read
How to move a ggplot2 legend with multiple rows to the bottom of a plot in R In this article, we are going to see how to draw ggplot2 legend at the bottom and with two Rows in R Programming Language. First, we have to create a simple data plot with legend. Here we will draw a Simple Scatter plot. Loading Library First, load the ggplot2 package by using library() function. li
3 min read
Draw Vertical Line to X-Axis of Class Date in ggplot2 Plot in R In this article, we will see how to draw Vertical Line to X-Axis of Class Date in ggplot2 Plot in R programming language. Here we are using Scatter Plot, you can draw any graph as per your requirement. First, load the ggplot2 package by using the library() function. Now we will create a DataFrame wi
4 min read
Multiple Line Plots or Time Series Plots with ggplot2 in R In this article, we will discuss how to plot Multiple Line Plots or Time Series Plots with the ggplot2 package in the R Programming Language. We can create a line plot using the geom_line() function of the ggplot2 package. Syntax: ggplot( df, aes( x, y ) ) + geom_line() where, df: determines the da
2 min read
How Do I Split My X-Axis into Multiple Plots in ggplot in R While handling large datasets in R, often while using functions like âplotâ, all the data is displayed in one single plot which can be confusing. In most cases, the division of the data into easily comprehensible portions is the only way to bring out trends more effectively. This can be achieved in
6 min read
Annotate Multiple Lines of Text to ggplot2 Plot in R In this article, we will see how to annotate Multiple Lines of text to ggplot2 Plot in R programming language. Let us first create a regular plot so that the difference is apparent, Example: R # Load Package library("ggplot2") # Create a DataFrame DF <- data.frame(X = runif(100, min=0, max=100),
2 min read