简体   繁体   English

如何在R中绘制像素精确图

[英]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! 因此,我更改为直接在PNG图像中绘制,该图像的分辨率以像素为单位,但是结果几乎相同!

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: 给我这张图片:

在此处输入图片说明

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. 我们可以看到黑色三角形上方有一个白色边距,我认为它不应该存在,因为所有高度都为100。并且所有图像周围都有黑色边框,我想也不应该在那里。 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! 毕竟,最终图像是1000x100像素!

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. 还有一件事:如果可能的话,我希望将整个过程绘制在屏幕上,在那里我可以看到它,最后只将其另存为PNG。 (Unless direct PNG draw is much faster.) (除非直接进行PNG绘制要快得多。)

That border is the box around the plot you created. 该边框是您创建的绘图周围的框。 Because you set the margins to 0, the rest of the plot, ie axis ticks and labels are outside of the window. 因为将边距设置为0,所以绘图的其余部分(即轴刻度和标签都在窗口之外)。 You can get rid of the box too by using axes=F . 您也可以通过使用axes=F摆脱盒子。 About the white lines near the bottom and top: by default, plot extends the limits a bit. 关于底部和顶部附近的白线:默认情况下, plot稍微扩展限制。 To disable this, use xaxs='i' and yaxs='i' . 要禁用此功能,请使用xaxs='i'yaxs='i' You can find all this in ?par . 您可以在?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)
}

结果

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

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