Hide top x-axis in doubleYScale plot in R

三世轮回 提交于 2019-12-11 02:47:29

问题


I'm plotting two xyplots with a doubleYScale plot. I would like to hide the top x-axis, but everything I tried so far either does nothing or hides all axes. Is this even possible?

library(lattice)
library(latticeExtra)
x<-seq(1:10)
y<-x^2
y2<-x*2

plot1<-xyplot(y~x, col="black", type="l", ylab="Label1", xlab="") 

plot2<-xyplot(y2~x, col="red", type="l", ylab="Label2", xlab="", scales=list(y=list(col="red")))

doubleYScale(plot1, plot2, add.axis=TRUE, add.ylab2 = TRUE, scales=list(x=list(draw=FALSE)))  

update(trellis.last.object(),
par.settings = simpleTheme(col = c("black", "red"), lty=c(1,1)), horizontal=F, scales=list(x=list(draw=T)))


回答1:


As you can see from the proposed solution below, lattice isn't really set up to easily do this particular thing. That said, it's pretty fully customizable, and with some work you can get what you're after. Here, with just a few inline comments, is code that will fully suppress that top axis:

library(lattice)
library(latticeExtra)
library(grid)

## Sample data
x <- seq(1:10)
y <- x^2
y2 <- x*2

## Prepare list of scales setting that suppresses ticks on top axis
myScales <- list(x = list(tck = c(1,0)))

## Prepare parameter settings, including setting the color used in
## plotting axis line to "transparent"
myTheme <- simpleTheme(col = c("black", "red"),
                       lty = c(1,1))
myTheme <- c(myTheme, list(axis.line = list(col = "transparent")))

## Write a custom axis function that only plots axis lines on the
## left, right, and bottom sides
myAxisFun <- function(side, line.col, ...) {
    if (side == "left") {
        grid.lines(x = c(0, 0), y = c(0, 1),
                   default.units = "npc")
    } else if (side == "right") {
        grid.lines(x = c(1, 1), y = c(0, 1),
                   default.units = "npc")
    } else if (side == "bottom") {
        grid.lines(x = c(0, 1), y = c(0, 0),
                   default.units = "npc")
    }
    axis.default(side = side, line.col = "black", ...)
}


## Construct two component plots
plot1 <- xyplot(y ~ x, col="black", type = "l",
                ylab = "Label1", xlab = "",
                par.settings = myTheme,
                scales = myScales,
                axis = myAxisFun) 
plot2 <- xyplot(y2 ~ x, col="red", type = "l",
                ylab = "Label2", xlab = "",
                par.settings = myTheme,
                scales = myScales,
                axis = myAxisFun)

## Meld the two plots 
doubleYScale(plot1, plot2, add.ylab2 = TRUE)



来源:https://stackoverflow.com/questions/52955237/hide-top-x-axis-in-doubleyscale-plot-in-r

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