removing the ticks on the 3rd and 4th axes in plots from library effects in R

牧云@^-^@ 提交于 2021-02-08 03:01:06

问题


I'm wondering if there is a way to remove the tickmarks (the axes) on the 3rd and 4th axes of the plot generated by library effects as shown below?

library(effects)
m <- lm(Fertility ~ ., data = swiss)
plot(allEffects(m), rug = FALSE)


回答1:


It doesn't look like the package authors choose to expose that propertly very easily. We could write our own version of plot.efflist which is doing most of the work here. Here's the alternative version

plot.efflist <- function (x, selection, rows, cols, graphics = TRUE, 
          lattice, ...) 
{
  lattice <- if (missing(lattice)) 
    list()
  else lattice
  if (!missing(selection)) {
    if (is.character(selection)) 
      selection <- gsub(" ", "", selection)
    pp <- plot(x[[selection]], lattice = lattice, ...)
    pp$x.scales$tck=c(1,0)
    pp$y.scales$tck=c(1,0)
    return(pp)
  }
  effects <- gsub(":", "*", names(x))
  neffects <- length(x)
  mfrow <- mfrow(neffects)
  if (missing(rows) || missing(cols)) {
    rows <- mfrow[1]
    cols <- mfrow[2]
  }
  for (i in 1:rows) {
    for (j in 1:cols) {
      if ((i - 1) * cols + j > neffects) 
        break
      more <- !((i - 1) * cols + j == neffects)
      lattice[["array"]] <- list(row = i, col = j, 
                                 nrow = rows, ncol = cols, more = more)
      pp <- plot(x[[(i - 1) * cols + j]], lattice = lattice, 
                 ...)
      # hack to turn off opposite side tick marks
      pp$x.scales$tck=c(1,0)
      pp$y.scales$tck=c(1,0)
      print(pp)
    }
  }
}
environment(plot.efflist) <- asNamespace("effects")

Basically we just call the plot.eff function as is, then modify the result to turn off the second set of ticks before plotting.

This returns

plot(allEffects(m), rug = FALSE)

Optionally you could try this approach as well

plot.eff <- function(...) {
  pp <- effects:::plot.eff(...)
  pp$x.scales$tck=c(1,0)
  pp$y.scales$tck=c(1,0)
  pp
}
environment(plot.eff) <- asNamespace("effects")
helpenv <- new.env(parent = asNamespace("effects"))
helpenv$plot.eff <- plot.eff
plot.efflist <- effects:::plot.efflist
environment(plot.efflist) <- helpenv

Here, rather than changing just the function that operators on efflist objects, we change the behavior for all eff objects. We do the rewrite but then also need to change the efflist version to find our new version first. This method keeps us from having to repeat any logic from these functions, but it does mean we make a bit of a mess with environments.



来源:https://stackoverflow.com/questions/62945745/removing-the-ticks-on-the-3rd-and-4th-axes-in-plots-from-library-effects-in-r

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