Knows_nothing
Knows_nothing

Reputation: 98

Plot a matrix in R - for loop not working

I have a 6*5 matrix, I want to plot it, by giving some coordinates as a different colour. I tried by using a list of plots, but plots all coordinate as last number

plottlist <- list()
for(i in 1:nrow(mat3)){
  for (j in 1:ncol(mat3)){
    plott<-ggplot() + theme_void()+geom_text(aes(1,1,label = mat3[i,j]))
    plot2 <- list(plott)
    plottlist[paste0(i,j)]<- plot2
  }

}
grid.arrange(grobs=plottlist)

output ouput

Upvotes: 0

Views: 47

Answers (1)

teunbrand
teunbrand

Reputation: 37953

If you want to just supply a vector to a layer that is not a column in a dataframe the layer can see, you'll likely want to do this outside the aes() function.

library(ggplot2)

mat3 <- matrix(sample(5*6), 6, 5)

plottlist <- list()
for(i in 1:nrow(mat3)){
  for (j in 1:ncol(mat3)){
    plott<-ggplot() + theme_void()+geom_text(aes(1,1), label = mat3[i,j])
    plot2 <- list(plott)
    plottlist[paste0(i,j)]<- plot2
  }
  
}
gridExtra::grid.arrange(grobs=plottlist)

Created on 2021-04-08 by the reprex package (v1.0.0)

Additionally, and I don't know if this is your real use-case, you can get a very similar plot without the need for looping if you convert your data to a long format.

library(ggplot2)

mat3 <- matrix(sample(5*6), 6, 5)

df <- reshape2::melt(mat3)

ggplot(df, aes(Var1, Var2, label = value)) +
  geom_text() +
  theme_void()

Created on 2021-04-08 by the reprex package (v1.0.0)

Upvotes: 1

Related Questions