Open In App

How to create a faceted line-graph using ggplot2 in R ?

Improve
Improve
Like Article
Like
Save
Share
Report

A potent visualization tool that enables us to investigate the relationship between two variables at various levels of a third-category variable is the faceted line graph. The ggplot2 tool in R offers a simple and versatile method for making faceted line graphs. This visual depiction improves our comprehension of the data’s patterns and trends.

Multiple small line plots organized in a grid-like pattern make up a faceted line graph. Within a certain category of the third variable, each line plot shows the relationship between the two relevant variables. This format makes it simple to compare the many categories, allowing us to spot patterns, trends, and similarities.

The main benefit of faceted line graphs is their capacity to present complex data succinctly and logically. We can see trends within each category and identify potential interactions or deviations by segmenting the data into smaller chunks based on the levels of the categorical variable.

In order to create a faceted line graph with ggplot2, we first define the information and aesthetics. We specify the categorical variable that will define the facets as well as the variables to be shown on the x and y axes. To add more details or increase clarity, we can alter the colors, line styles, and labels within each facet.

Method 1: Using facet_grid() 

First, a data frame is created, and then we create a faceted Line Graph by adding the facet_grid() function to geom_line.

Syntax : facet_grid(facets, …)

Parameters :

  • facets : this parameter is necessary to use with facet_grid. which specify the formula with the rows on LHS and columns on RHS. the dot parameter used in the formula to indicate that there should be no faceting on this dimension (row or column).
  • … : facet_grid function has also many parameters such as scale, space, margins, shrink, etc . but they are not necessary to use. they all have some default values but if we want to change them than we can use them. But for faceting first parameter is enough.

Return : Facets on a Plot.

Syntax In Use : 

facet_grid(row ~ column)

As in the above syntax, we use the Facets vector to indicate columns and nothing for rows. For specifying nothing, we use a dot parameter like facet_grid(. ~ Facets). This will return vertical facets on the plot and to draw horizontal facets, we simply have to interchange the dot parameter and facets vector in the facet_grid() function.

Example :

R




# Load Library
library("ggplot2")
 
# Create DataFrame
DF <- data.frame(X = rnorm(60),                                  
                 Y = rnorm(60),
                 Facets = c("Facet 1", "Facet 2",
                            "Facet 3", "Facet 4"))
 
# Create Faceted LineGraph with Vertical Facets.
ggplot(DF, aes(X, Y)) +                                    
  geom_line(color = "green", size = 1) +
  facet_grid(. ~ Facets)


Output:
 

facet_grid linegraph

Faceted LineGraph with vertical facets using facet_grid

Method 2: Using facet_wrap() 

We can also create Faceted Line Graph using the facet_wrap() function, which generally better uses screen space than facet_grid() as it wraps a one-dimensional sequence of panels into two dimensional. That means it creates 4 facets for our DataFrame a 2×2 manner. Using its parameters, we also change the number of rows and columns of facets.

Syntax : facet_wrap(facets, nrow, ncol, …)

Parameters :

  • facets : same as facets parameter of facet_grid functionas we discussed above. it specify the formula with row at LHS and column at RHS i.e row ~ column.
  • nrow : Number of rows of facets.
  • ncol : Number of columns of facets.
  • … : facet_wrap has also some parameters that doesn’t matter as much as they have it’s Default values. We can use them in some special case.

Return : Convert 1D sequence of facets into 2D.

Example :

R




# Load Library
library("ggplot2")
 
# Create a DataFrame for Plotting
DF <- data.frame(X = rnorm(60),                                  
                 Y = rnorm(60),
                 Facets = c("Facet 1", "Facet 2",
                            "Facet 3", "Facet 4"))
 
# Create a Faceted LineGraph using
# facet_wrap Function.
ggplot(DF, aes(X, Y)) +                                    
  geom_line(color = "green", size = 1) +
  facet_wrap(. ~ Facets)


Output:

facet_wrap linegraph

2×2 Faceted LineGraph using facet_wrap 

By default, the output came as a grid for this one. But it can be changed using nrow and ncol parameters with an appropriate value.

Example :

R




# Load Library
library("ggplot2")
 
# Create a DataFrame for Plotting
DF <- data.frame(X = rnorm(60),                                  
                 Y = rnorm(60),
                 Facets = c("Facet 1", "Facet 2",
                            "Facet 3", "Facet 4"))
 
# Create a Faceted LineGraph using facet_wrap
# Function with changed number of rows.
ggplot(DF, aes(X, Y)) +                                    
  geom_line(color = "green", size = 1) +
  facet_wrap(. ~ Facets, nrow = 4)


Output:

facet_wrap linegraph

Faceted LineGraph using facet_wrap with different numbers of rows

Change the color of lines and Increase the size of lines:

R




library(ggplot2)
 
# Create a DataFrame for Plotting
DF <- data.frame(X = rnorm(60),                                  
                 Y = rnorm(60),
                 Facets = c("Facet 1", "Facet 2",
                            "Facet 3", "Facet 4"))
 
# Create a Faceted Line Graph using facet_wrap
# Function with changed number of rows and increased line size.
ggplot(DF, aes(X, Y)) +                                    
  geom_line(color = "blue", size = 2.5) +  # Increase line size to 2
  facet_wrap(. ~ Facets, nrow = 4)


Output:

Faceted LineGraph using facet_wrap with different number of rows

Faceted LineGraph using facet_wrap with a different number of rows

  • adjusted the size and color parameter in the geom_line function in this code from 1 to 2.5 and green to blue. By modifying the value, you can further alter the line width to suit your preferences.
     

Increase the number of Facets in the plot:

R




library(ggplot2)
 
# Create a DataFrame for Plotting
DF <- data.frame(X = rep(rnorm(60), 9),                                  
                 Y = rnorm(540),
                 Facets = rep(paste0("Facet ", 1:9), each = 60))
 
# Create a Faceted Line Graph using facet_wrap
# Function with changed number of rows and increased line size.
ggplot(DF, aes(X, Y)) +                                    
  geom_line(color = "blue", size = 2.5) +  # Increase line size to 2
  facet_wrap(. ~ Facets, nrow = 3)


Output:

Faceted LineGraph using facet_wrap with a different number of rows

Faceted LineGraph using facet_wrap with a different number of rows

Added nine facet levels to the DF data frame in this code by iterating through the values for “Facet 1” through “Facet 9” for every cluster of 60 rows. Then, to organize the plots in a 3×3 grid, I changed the facet_wrap method to have nrow = 3.

conclusion: 

faceted line graphs created in R with ggplot2 offer an aesthetically pleasing and instructive way to display complex data. We can compare patterns and trends by segmenting the data into smaller plots depending on a category variable. This method helps in comprehending the connections between variables and locating variations between groups. We can construct intelligent and aesthetically pleasing faceted line graphs for data analysis and communication thanks to the versatility of ggplot2.
 



Last Updated : 08 Jun, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads