Rodrigo
Rodrigo

Reputation: 5119

How to draw pixel accurate plots in R

I want to represent a matrix as an image, so I want to use the plot as if each pixel was a cell in the matrix. But for some reason I can't. First I've drawn on screen, where the resolution is in inches. So I changed to draw directly in a PNG image, where the resolution is specified in pixels, but the result is almost the same!

The following code

png(file="graf.png",width=1000,height=100)
par(mar=c(0,0,0,0))
plot(NULL,xlim=c(1,1000),ylim=c(1,100))
for (i in 1:100) {
    p1 <- i
    range <- i
    p2 <- p1+range
    segments(p1,i,p2,i)
}
dev.off()

is giving me this image:

enter image description here

We can see there is a white margin above the black triangle, I think it shouldn't be there, since all heights are 100. And there is a black border around all the image, I think it shouldn't be there either. And the triangle ain't "smooth", the two sides should be completely straight, but there are "breaks" in some points, as if some "rounding" is going on somewhere. Why is that? And why the bottom angle of the triangle is so far from the corner of the image? The final image is 1000x100 pixels, after all!

One more thing: if possible, I'd prefer to draw the whole process on screen, where I can see it, and only in the end save it as PNG. (Unless direct PNG draw is much faster.)

Upvotes: 0

Views: 1045

Answers (1)

koekenbakker
koekenbakker

Reputation: 3604

That border is the box around the plot you created. Because you set the margins to 0, the rest of the plot, i.e. axis ticks and labels are outside of the window. You can get rid of the box too by using axes=F. About the white lines near the bottom and top: by default, plot extends the limits a bit. To disable this, use xaxs='i' and yaxs='i'. You can find all this in ?par.

par(mar=c(0,0,0,0))
plot(NULL,xlim=c(1,1000),ylim=c(1,100), type='n', axes=F, yaxs='i',xaxs='i')
for (i in 1:100) {
  p1 <- i
  range <- i
  p2 <- p1+range
  segments(p1,i,p2,i)
}

result

Upvotes: 1

Related Questions