Error ggplot2 doesn’t know how to deal with data of class matrix


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

If you are trying to use ggplot2 with a matrix object, you may run into the following error message:

ggplot2 doesn’t know how to deal with data of class matrix

The problem is that ggplot2 expects data to be in a specific format, called a data frame. A data frame is basically a table, where each column is a variable, and each row is an observation.

You can convert a matrix object into a data frame using the function:


What is ggplot2?

ggplot2 is a plotting system for R, based on the grammar of graphics, which tries to take the good parts of base and lattice graphics and none of the bad parts. It takes care to never break your existing code.

The main idea is to design a graphic as a succession of layers. You start with your data, then add “aesthetics”, then add statistical transformations as needed, then add facets to split your data up into subsets, then finally you add other annotations.

What is a matrix?

A matrix is a two-dimensional array of data, usually consisting of numbers. In R, matrices are created using the matrix() function. For example:

matrix(1:9, nrow = 3)
[,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 9

This creates a 3×3 matrix, with the values 1-9 going down each column. Matrices can be created with other types of data as well:

matrix(c(“A”, “B”, “C”, “D”, “E”), nrow = 5)


[1,] “A”
[2,] “B”
[3,] “C”
[4,] “D”
[5,] “E”

Why does ggplot2 have difficulty with matrix data?

There are a few reasons why ggplot2 might have difficulty with matrix data. First, matrix data doesn’t have a “long” format, which is the format that ggplot2 prefers. Second, matrix data often has missing values, which can trip up ggplot2. Finally, the column names of matrix data are often not very informative, which can make it hard to create good-looking plots.

How can you get around this problem?

If you have a matrix of data, you can use the function to convert it to a data frame. This will allow ggplot2 to properly interpret the data.


The error message is telling you that ggplot2 doesn’t know how to deal with data of class matrix. A matrix is a two-dimensional data structure, like a data frame, but it can only contain numeric values. To fix the error, you need to convert your matrix to a data frame:

matrix_df =

Leave a Reply

Your email address will not be published.