Plotting Multiple Lines to One ggplot2 Graph in R (Example Code)
In this post you’ll learn how to plot two or more lines to only one ggplot2 graph in the R programming language.
Setting up the Example
data(iris) # Loading iris data iris <- iris[ , 1:4] # Remove non-numeric data iris$x <- 1:nrow(iris) # Add counter head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width x # 1 5.1 3.5 1.4 0.2 1 # 2 4.9 3.0 1.4 0.2 2 # 3 4.7 3.2 1.3 0.2 3 # 4 4.6 3.1 1.5 0.2 4 # 5 5.0 3.6 1.4 0.2 5 # 6 5.4 3.9 1.7 0.4 6 |
data(iris) # Loading iris data iris <- iris[ , 1:4] # Remove non-numeric data iris$x <- 1:nrow(iris) # Add counter head(iris) # Sepal.Length Sepal.Width Petal.Length Petal.Width x # 1 5.1 3.5 1.4 0.2 1 # 2 4.9 3.0 1.4 0.2 2 # 3 4.7 3.2 1.3 0.2 3 # 4 4.6 3.1 1.5 0.2 4 # 5 5.0 3.6 1.4 0.2 5 # 6 5.4 3.9 1.7 0.4 6
We have to install and load the ggplot2 & reshape2 packages:
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 install.packages("reshape2") # Install & load reshape2 package library("reshape2") |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 install.packages("reshape2") # Install & load reshape2 package library("reshape2")
Example: Draw Multiple Lines in One ggplot2 Graph (Iris Flower Data)
iris_long <- melt(iris, id = "x") # Transforming data to long format head(iris_long) # Printing head of long iris data # x variable value # 1 1 Sepal.Length 5.1 # 2 2 Sepal.Length 4.9 # 3 3 Sepal.Length 4.7 # 4 4 Sepal.Length 4.6 # 5 5 Sepal.Length 5.0 # 6 6 Sepal.Length 5.4 |
iris_long <- melt(iris, id = "x") # Transforming data to long format head(iris_long) # Printing head of long iris data # x variable value # 1 1 Sepal.Length 5.1 # 2 2 Sepal.Length 4.9 # 3 3 Sepal.Length 4.7 # 4 4 Sepal.Length 4.6 # 5 5 Sepal.Length 5.0 # 6 6 Sepal.Length 5.4
ggplot(iris_long, # Drawing ggplot2 plot aes(x = x, y = value, color = variable)) + geom_line() |
ggplot(iris_long, # Drawing ggplot2 plot aes(x = x, y = value, color = variable)) + geom_line()
Further Resources
Have a look at the following R tutorials. They illustrate similar topics as this post: