【问题标题】:How to amend existing axes on a plot in R?如何在 R 中修改绘图上的现有轴?
【发布时间】:2018-10-19 07:51:21
【问题描述】:

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

这是代码:

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.

结果是这样的:

【问题讨论】:

  • 使用ggplot 并将绘图保存到一个对象中。然后,您可以在之后添加内容或更改布局,而无需再次计算绘图。

标签: r plot axis axes


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多