繁体   English   中英

如何将geom_raster()输出到栅格图像?

[英]How to output geom_raster() to a raster image?

我正在进行定量图像分析,并使用ggplot2可视化结果。 输出包含原始图像中每个像素的一个数据点。

geom_raster()很好地显示了我在R中的数据。但是,输出与结果相对应的栅格图像会很好。 这样,我可以使用轻量级的图像查看器(例如feh )浏览几个派生图像,并且像素将完美对齐。

是否有一种简单的方法可以将像素( 像素)输出到图像文件? 没有图例,没有轴,只有像素。 假设我的data.framerowcol ,并且所需的输出分辨率也是已知的。

这是一种方法:

library(ggplot2)
library(reshape2) # for melt(...)

n <- 100
set.seed(1)   # for reproducible example
img <- matrix(rnorm(n^2,30,3),nc=n)
gg <- melt(data.frame(x=1:n,img),id="x")
ggplot(gg) + geom_raster(aes(x=x,y=variable,fill=value))+
  scale_x_continuous(expand=c(0,0))+   # get rid of extra space on x-axis
  guides(fill=FALSE)+                  # turn off color legend
  theme(axis.text=element_blank(),     # turn off the axis annotations
        axis.ticks=element_blank(),
        axis.title=element_blank())

感谢jlhoward为我指出正确的方向。 还有更多缺少的成分-例如,如果没有labs(x=NULL, y=NULL) ,则输出PNG的底部和左侧将带有白色边框。

我决定我的解决方案应该包括两个部分:

  1. 制作一个ggplot对象以可视化我的数据。 (此步骤与通常相同。)
  2. 调用通用函数来处理所有烦人的细节,这些细节对于将绘图作为像素完美的PNG输出是必需的。

这是一个这样的功能。

BorderlessPlotPng <- function(plot, ...) {
  # Write a ggplot2 plot to an image file with no borders.
  #
  # Args:
  #   plot:  A ggplot2 plot object.
  #   ...:  Arguments passed to the png() function.
  require(grid)
  png(type='cairo', antialias=NULL, units='px', ...)
  print(plot
        + theme(plot.margin=unit(c(0, 0, -0.5, -0.5), 'line'),
                axis.text=element_blank(),
                axis.ticks=element_blank(),
                axis.title=element_blank(),
                legend.position='none')
        + scale_x_continuous(expand=c(0, 0))
        + scale_y_continuous(expand=c(0, 0))
        + labs(x=NULL, y=NULL)
        )
  dev.off()
}

为了看到它的实际效果,下面是一些综合数据的图表。 (出于演示目的,我将每个输出像素的宽度设置为10像素。)

# Synthetic data.
width <- 64
height <- 48
d <- data.frame(row=rep(1:height, each=width),
                col=rep(1:width, height),
                x=rnorm(n=width * height))

# Construct and print the plot.
library(ggplot2)
plot <- (ggplot(data=d, aes(x=col, y=height + 1 - row, fill=x))
         + geom_raster()
         + scale_fill_gradient2()
         )
pixel_size <- 10
BorderlessPlotPng(plot,
                  filename='test.png',
                  width=width * pixel_size,
                  height=height * pixel_size)

输出: 运行以上代码可能获得的一种输出。

当然,以pixel_size <- 1运行将为您提供1:1的图像,您可以通过前后翻转将其与原始图像进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM