How does R's tikzDevice deal with raster images?

194 views Asked by At

I have read, if tikz takes a raster image it is to be stored as png. Having that, tikz produces the rest of the graph around it and include the raster image in the final tex-file back again.

Now I have the following:

pic <- T
if(pic)
{
  tikz(file=paste(plotpath,"Rohdaten_S1_S2_D21.tex",sep=""),width=width,height=height,engine = "pdftex",)
  #png(filename=paste(plotpath,"Rohdaten_S1_S2_D6.png",sep=""),width=width,height=height,res=res,units="in")
  par(mfrow=c(2,1),mar=c(1.1,3,2,0),mgp=c(1.5,0.5,0),ps=f.size,cex=1,xaxt="n")
}
if(!pic) par(mfrow=c(2,1),mar=c(1,4,3,0))
for(i in 1:2)
{
  x <- sensors[[i]]$time
  y <- sensors[[i]]$depth
  z <- sensors[[i]]$velo
  image(x,y,z)
  #   plot.image(x,y,z
#              ,xlim=c(max(x)-400,max(x)),zlim=2*c(-1,1)
#              ,xlab="",ylab="$d/\\mathrm{m}$",zlab="$v/(\\mathrm{mm/s})$"
#              ,z.adj=c(0,0),ndz=5,z.cex=1
#              )  
  abline(v=(1:10)/0.026+par("usr")[1],lty=2)
  if(!pic) abline(h=(1:floor(max(y/0.02)))*0.02)
  mtext(text=paste("Sensor",i),side=3,line=0.1,adj=0)
  par(mar=c(3,3,0.1,0),xaxt="s")
}
title(xlab="t/s")
if(pic) dev.off()

even the simple image() function will produce a 100MB large .tex file. No png is produced, everything is in the .tex file?!

What am I doing wrong? Is there a switch to be set TRUE? What do I have to do to put the rasterimage apart from the nice looking text.

Thank you for your help.

1

There are 1 answers

0
Seily On BEST ANSWER

The solution is quite simple, but not obvious.

  1. the image()-function in R produces vector graphics in the first instance. There is a switch image(...,useRaster = T) with which one can force the image()-function to produce raster graphics.
  2. the image()-function aspects a regular grid (quadratic pixels). Otherwise an error occurs.

How to get a regular grid?

Suppose you have an image with the coordinates x[],y[] and the scalar matrix z[,]. Then the re-sampled regular grid can be calculated:

x.new<-seq(min(xlim),max(xlim),length.out=dim.max[1])
y.new<-seq(min(ylim),max(ylim),length.out=dim.max[2])

z<-apply(z,2,function(y,x,xout) return(approx(x,y,xout=xout+min(diff(x))/2,method="constant",rule=2)$y),x,x.new)
z<-t(apply(z,1,function(y,x,xout) return(approx(x,y,xout=xout+min(diff(x))/2,method="constant",rule=2)$y),y,y.new))

tikz(file ='a.tex',width = 2, height = 2)
    image(x,y,z,useRaster = T)
dev.off()

The important things are the method = "constant" and the rule = 2 statements in the approx()-function. These enables a "shifting" to the regular grid.

Applying all this and tikz() will split the picture in a a.tex-file and a a_ras1.png-file.

I hope this will help sombody programming R and using tikzDevice to produce pictures for tex documents.