lodomi
lodomi

Reputation: 67

How to plot png image in ggplot2?

The image does not display properly, it is rotated 90 degrees to the left.

library("png")
library("ggplot2")

download.file("https://upload.wikimedia.org/wikipedia/commons/7/70/Example.png",
              "wiki.png", mode = 'wb')
img = readPNG("wiki.png")

grd = expand.grid(1:178, 1:172)
dim(img) = c(178 * 172, 3)
img = as.data.frame(img)
img = cbind(grd, img)
colnames(img) = c("X", "Y", "R", "G", "B")
img$RGB = rgb(img$R, img$G, img$B)

ggplot(img, aes(x = X, y = Y, fill = RGB)) +
  geom_raster() +
  scale_fill_identity()

Upvotes: 3

Views: 917

Answers (2)

Ben Bolker
Ben Bolker

Reputation: 226107

This is a standard problem with plotting conventions vs. image conventions.

How about

ggplot(img, aes(x = Y, y = X, fill = RGB)) + 
      geom_raster() + scale_fill_identity() +   scale_y_reverse()

?

Upvotes: 2

Gregor Thomas
Gregor Thomas

Reputation: 145765

Your raster image is essentially a matrix - with the first row, first column at the top left corner, and the typical matrix ordering of dimensions (row, column).

ggplot's default is for plotting data in Cartesian coordinates, where, if your plot has all positive values the "start" (origin) is the bottom left corner, and the typical ordering of dimensions is (x, y).

These are very different systems, so you'll need to translate between the two of them to take this approach: aes(x = Y, y = -X, fill = RGB) - though to make things clearer you may want to choose different names than X and Y for your image coordinates.

Upvotes: 4

Related Questions