首页 > 解决方案 > 如何在 R 中修改绘图上的现有轴?

问题描述

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

这是代码:

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.

结果是这样的: 在此处输入图像描述

标签: rplotaxisaxes

解决方案


至少有两种方法可以保存 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

推荐阅读