Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove PNG plot margins

Tags:

plot

r

png

r-sp

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()

plot

like image 815
jhhwilliams Avatar asked Mar 24 '26 03:03

jhhwilliams


1 Answers

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()
like image 160
jhhwilliams Avatar answered Mar 26 '26 17:03

jhhwilliams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!