Remove PNG plot margins

二次信任 提交于 2019-12-11 03:37:41

问题


I am trying to get rid of the top and bottom margins of a SpatialPolygons plot. I have tried setting the margins to c(0,0,0,0) but this only changes the left and right margins.

When plotting in RStudio, the top and bottom margins are 0 but the left and right are not.

library(sp)

coords <- cbind(c(631145, 631757, 631928, 631664, 631579, 631281),
                c(6967640, 6967566, 6968027, 6967985, 6968141, 6968009))
poly <- Polygons(list(Polygon(coords)),"coords")
poly.sp <- SpatialPolygons(list(poly))

par(mar = rep(0, 4), xaxs='i', yaxs='i')
plot(poly.sp, bg="yellow")

png('poly.png')
par(mar = rep(0, 4), xaxs='i', yaxs='i')
plot(poly.sp, bg="yellow")
dev.off()


回答1:


I solved the problem by calculating the aspect ratio of the polygon that I am trying to plot and then setting the plot width and height.

This might not be the most elegant solution but it does the job.

library(sp)

coords <- cbind(c(631145, 631757, 631928, 631664, 631579, 631281),
                c(6967640, 6967566, 6968027, 6967985, 6968141, 6968009))
poly <- Polygons(list(Polygon(coords)),"coords")
poly.sp <- SpatialPolygons(list(poly))

width <- poly.sp@bbox[3] - poly.sp@bbox[1]
height <- poly.sp@bbox[4] - poly.sp@bbox[2]
aspect <- height / width

png('poly.png', width = 10, height = 10*aspect, units = 'in', res = 300)
par(mar = rep(0, 4), xaxs='i', yaxs='i')
plot(poly.sp, bg="yellow")
dev.off()


来源:https://stackoverflow.com/questions/32268654/remove-png-plot-margins

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!