Ingolifs
Ingolifs

Reputation: 311

r ggplot2 making basic 2d image

A lot of the functionality of ggplot2 mystifies me, and all the tutorial examples seem to be at a level one higher than where I'm at.

I just want to make a basic raster image, like this:

M <- matrix(rnorm(625),nrow=25,ncol=25)
image(M,useRaster=TRUE)

basic r plot of 2d noise

How do I do this in ggplot2? I've tried multiple things, but they typically ask for a data frame. If M is converted into a data frame, it gives a different error. I've never really understood the ggplot2 philosophy, or how the package is intended to be used.

Upvotes: 2

Views: 775

Answers (1)

Johan Rosa
Johan Rosa

Reputation: 3152

ggplot2 API works only with data.frame objects and one must convert the data to that format to use the package.

In your case I recommend two options to convert the matrix to a data.frame with tidy format.

Original data

m <- matrix(rnorm(625),nrow=25,ncol=25)

With the raster package

You can easy convert a raster object into a data frame like this

library(raster)
m_df <- as.data.frame(raster(m), xy = TRUE)

m_df %>%
  ggplot(aes(x = x, y = y, fill = layer)) +
  geom_raster()

enter image description here

With tidyverse functions

You can do this using the tidyverse as well, but the process involves more steps.

library(tidyverse)

m_df <- m %>%
  as.data.frame() %>%
  rowid_to_column(var = 'y') %>%
  pivot_longer(-y, names_to = "x", values_to = "layer") %>%
  mutate(x = parse_number(x))

m_df %>%
  ggplot(aes(x = x, y = y, fill = layer)) +
  geom_raster()

enter image description here

Why all those operations:

They're mostly necessary, especially the pivot_longer part. (One of the downsides of ggplot is that it insists on everything being in long format. In the long run this adds a huge amount of flexibility, but the first step of converting your data to long format can be daunting.) - @Ben Bolker

PS: If you have a considerable amount of images to work with, remember that you can use functional programming. Try to create a function to do de data manipulation and use a loop or another iterating method.

Upvotes: 4

Related Questions