如何修改R中图上的现有轴?

时间:2018-05-09 08:53:49

标签: r plot axis axes

我正在编辑一个情节。我正在使用轴格式化出错并希望修复它们。但是,如果我在错误的代码之后编写了正确的代码,则新轴将添加到现有轴的顶部,而不是替换它们。有没有更好的方法来修改轴而不从头开始绘制图?

这是代码:

library("sp")

#Prepare data
data("meuse.riv")
meuse.lst <- list(Polygons(list(Polygon(meuse.riv)),"meuse.riv"))
meuse.sr <- SpatialPolygons(meuse.lst)

#Create the plot
plot(meuse.sr, axes = F)
axis(1, at = c(178000 + 0:2 * 2000), cex.axis = 0.7)
#Code with a mistake: I need 3 stretches insted of 2

axis(1, at = c(178000 + 0:3 * 2000), cex.axis = 0.7)
#Right code but new axis is added to the old one; it can be seen because old part looks bolder

axis(2, at = c(326000 + 0:3 * 4000))
#Code with a mistake: I need smaller font (cex.axis = 0.7)

axis(2, at = c(326000 + 0:3 * 4000), cex.axis = 0.7)
#Right code but new labels are laid over the old ones. They are not readable.

结果如下: enter image description here

1 个答案:

答案 0 :(得分:0)

至少有两种方法可以保存R基础图形并重新绘制它:

library("sp")

pdf(NULL)
dev.control(displaylist="enable")
#Prepare data
data("meuse.riv")
meuse.lst <- list(Polygons(list(Polygon(meuse.riv)),"meuse.riv"))
meuse.sr <- SpatialPolygons(meuse.lst)

#Create the plot
plot(meuse.sr, axes = F)
axis(1, at = c(178000 + 0:2 * 2000), cex.axis = 0.7)

my.plot1 <- recordPlot()
invisible(dev.off())

# Display the saved plot
grid::grid.newpage()
my.plot1

更简单的方法是使用pryr库:

library(pryr)

my.plot2 %<a-% {

  #Prepare data
  data("meuse.riv")
  meuse.lst <- list(Polygons(list(Polygon(meuse.riv)),"meuse.riv"))
  meuse.sr <- SpatialPolygons(meuse.lst)

  #Create the plot
  plot(meuse.sr, axes = F)
  axis(1, at = c(178000 + 0:2 * 2000), cex.axis = 0.7)
}
my.plot2