Error: ggplot2 doesn't know how to deal with data of class matrix?

Muhammed Eltabakh picture Muhammed Eltabakh · Feb 6, 2017 · Viewed 8.6k times · Source

How can I make ggplot work with this data I tried normal plotting and it works just fine, but I want better visualization when I use ggplot, it gives me the above error, How do I fix this ?

This is an implementation of spectral clustering algorithm. and the code works well and the data is classified correctly. I just need to show this now .

library(ggplot2)

input_data <- as.matrix(read.table("SpectData.txt"))
colnames(input_data) <- c("x1", "x2")

#1- Define Weights matrix
W <- matrix(0,nrow = nrow(input_data),ncol = nrow(input_data))

#2- Define Degree Matrix
D <- matrix(0,nrow = nrow(input_data),ncol = nrow(input_data))

calculateWeight <- function(x1,x2,sigma) {
  result <- exp(- (norm(x2-x1,type = "2"))^2/ (2*sigma^2))
  result
}

calcWieghtMatrix <- function(sigma) {
  for(i in 1: nrow(W)){
   for(j in 1: nrow(W)){
    if(i == j){
      next
    }
    if( W[i,j] != 0){
      next
    }

    W[i,j] <<- calculateWeight(input_data[i,],input_data[j,],sigma)
    W[j,i] <<- W[i,j]
  }
 }
}    

calcDegreeMatrix <- function()  {
  for( i in 1:nrow(input_data)){
    D[i,i] <<- sum(W[i,])
  }
}

executeSpectralClustring <- function (sigma,numberOfClusters){
  calcWieghtMatrix(sigma)
  calcDegreeMatrix()
  L <<- D - W
  eigenDecompostion <- eigen(L,symmetric = FALSE)
  index <- ncol(eigenDecompostion$vectors)-1
  eigenVector <- eigenDecompostion$vectors[,index] 
  cl <- kmeans(eigenVector,numberOfClusters)
  ggplot(input_data,col = cl$cluster)
}    

executeSpectralClustring(0.01,2)

Answer

miPlodder picture miPlodder · Feb 17, 2018

Just convert class matrix to data frame and do make sure that you store that data frame in another object.

dataFrame<-data.frame(classMatrix)

Now, use ggplot on this object dataFrame.