Error using corrplot
Asked Answered
T

3

15

I need help with interpreting an error message using corrplot.

Here is my script

install.packages("ggplot2")
install.packages("corrplot")
install.packages("xlsx")

library(ggplot2)
library(corrplot)
library(xlsx)

#set working dir
setwd("C:/R")
#read xlsx data into R
df <- read.xlsx("TP_diff_frame.xlsx",1)
#set column as index
rownames(df) <- df$country
#remove column
df2<-subset(df, select = -c(country) )
#round values to to decimals


corrplot(df2, method="shade",shade.col=NA, tl.col="black", tl.srt=45)

My df2:

> df2
                     a    b     c     d     e    f    g
Sweden            0.09 0.19  0.00 -0.25 -0.04 0.01 0.00
Germany           0.11 0.19  0.01 -0.35  0.01 0.02 0.01
UnitedKingdom     0.14 0.21  0.03 -0.32 -0.05 0.00 0.00
RussianFederation 0.30 0.26 -0.07 -0.41 -0.09 0.00 0.00
Netherlands       0.09 0.16 -0.05 -0.26  0.02 0.02 0.01
Belgium           0.12 0.20  0.01 -0.34  0.01 0.00 0.00
Italy             0.14 0.22  0.01 -0.37  0.00 0.00 0.00
France            0.14 0.24 -0.04 -0.34  0.00 0.00 0.00
Finland           0.16 0.17  0.01 -0.26 -0.08 0.00 0.00
Norway            0.15 0.21  0.10 -0.37 -0.09 0.00 0.00

And the error message:

> corrplot(df2, method="shade",shade.col=NA, tl.col="black", tl.srt=45)

Error in matrix(unlist(value, recursive = FALSE, use.names = FALSE), nrow = nr, : length of 'dimnames' [2] not equal to array extent

Threadgill answered 15/1, 2014 at 14:59 Comment(1)
Debugging: try dim(df2) and compare with length(dimnames(df2))Jacobin
T
38

I think the problem is that you are plotting the data frame instead of the correlation matrix. Try to change the last line to this:

corrplot(cor(df2), method="shade",shade.col=NA, tl.col="black", tl.srt=45)

The function cor calculates the correlation matrix, which is what you need to plot

Tega answered 15/1, 2014 at 15:42 Comment(2)
Oh, I thought you could pass a datframe into corrplot to generate a heatmap. What is really what I was looking for in this case, and also to plot the values of the datafram on the correlation plot. I guess I was on the wrong path...It worked great with your answer though, thxThreadgill
@Threadgill Glad it worked. I used to make the same mistake at the beginning.Tega
Z
4

In order to use the corrplot package for heatmap plots you should pass your data.frame to a matrix and also use the is.corr argument.

df2 <- as.matrix(df2)

corrplot(df2, is.corr=FALSE)
Zoller answered 12/7, 2016 at 20:13 Comment(1)
This question (from 2014) has a highly-upvoted answer that says basically the same thing as yours.Neurath
L
3

Another option is to break it up into two lines of code.

df2 <- cor(df, use = "na.or.complete")
corrplot(df2, method="shade",shade.col=NA, tl.col="black", tl.srt=45)

I'd run a simple corrplot (e.g. corrplot.mixed(df2)) make sure it works, then get into the fine tuning and aesthetics.

Landau answered 1/6, 2014 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.