The corrplot()
function is used to plot a correlation matrix in R. This function provides a visual representation of the correlation matrix, making it easier to understand the relationships between variables.
In this article, we will explore how to use the corrplot()
function in R to create a correlation matrix with examples.
Method: Use corrplot() Function
To plot a correlation matrix, we need to load the corrplot
package and use the corrplot()
function.
Here’s the syntax:
library(corrplot)
corrplot(correlation_matrix)
The following example shows how to use the corrplot()
function to plot a correlation matrix in R.
Using corrplot() Function
Suppose we want to plot a correlation matrix created from a data frame.
First, we need to use the cor()
function to create the correlation matrix, and then we can use the corrplot()
function to plot it:
# Import library
library(corrplot)
# Create data frame
df <- data.frame(Pressure1=c(78.2, 88.2, 71.7, 80.21, 84.21, 82.56, 72.12, 73.85),
Temperature=c(35, 36, 37, 38, 32, 30, 31, 34),
Pressure2=c(12, 13, 11, 12, 14, 15, 13, 15))
# Create correlation matrix
correlation_matrix <- cor(df)
# Plot correlation matrix
corrplot(correlation_matrix)
Output: 👇️
In this example, the cor()
function calculates the correlation matrix for the Pressure1
, Temperature
, and Pressure2
columns of the data frame, and the corrplot()
function plots the correlation matrix.