1

I'm having real trouble trying to write some functions with ggplot() inside.

Here's a simplified version of what I'm trying to do. This works as expected:

testdata <- matrix(1:10, 
                   nrow = 5)
ggplot() + geom_point(aes(testdata[,1], 
                          testdata[,2]))

Putting the same code in a function:

mygg <- function(data){
  ggplot() + geom_point(aes(data[,1], 
                            data[,2]))
}
mygg(testdata)  

Gives the error:

Error in data[, 1] : object of type 'closure' is not subsettable

And when I replace aes with aes_string, only the first row of my matrix is plotted.

It does work when I rename my matrix 'data', but the whole point is that I want to plot a bunch of matrices with different names.

I've done my best to search the forums, and realise that my question is basically a duplicate, but I've been completely unable to find a solution to my specific issue.

TFinch
  • 361
  • 2
  • 9

1 Answers1

2

I played around with it for a minute and found that you needed to use the variable names in the aes() method. In addition, I coerced the matrix into a data frame because ggplot complained about that as well.

Replicating the problem, showing the output that lead to a solution.

> mygg(testdata)
Error in data[, 1] : object of type 'closure' is not subsettable
> testdata
  V1 V2
1  1  6
2  2  7
3  3  8
4  4  9
5  5 10
> testdata <- matrix(1:10, nrow = 5)
> testdata <- as.data.frame(testdata)
> mygg <- function(data){
+   ggplot(data) + geom_point(aes(x = V1, y = V2))
+ }
> mygg(testdata)
> # outputs the plot

Prettier code

library('ggplot2')
testdata <- matrix(1:10, nrow = 5)
testdata <- as.data.frame(testdata)
mygg <- function(data){
  ggplot(data) + geom_point(aes(x = V1, y = V2))
}
mygg(testdata)

In general, you'll want to make your function flexible enough to account for things like variable names (maybe using the names() function).

theWanderer4865
  • 861
  • 13
  • 20