如何在ggplot2中绘制png图片?

问题描述 投票:2回答:2

图片不能正常显示,向左旋转90度。

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()
r ggplot2
2个回答
3
投票

你的光栅图像本质上是一个矩阵--第一行、第一列在左上角,典型的矩阵维度排序(行、列)。

ggplot如果你的绘图都是正值,那么 "开始"(原点)是左下角,典型的维度排序是(x,y)。

这些都是非常不同的系统,所以你需要在这两个系统之间进行转换来采取这种方法。aes(x = Y, y = -X, fill = RGB) - 不过为了让事情更清楚,你可能会想选择不同的名称,而不是... XY 为您的图像坐标。


2
投票

这是绘图约定与图像约定的标准问题。

那么

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

?

© www.soinside.com 2019 - 2024. All rights reserved.