【问题标题】:Custom Lattice Function: Getting Colors Correct Across Panels自定义格子函数:跨面板获取正确的颜色
【发布时间】:2015-05-01 23:15:10
【问题描述】:

我正在尝试控制自定义 Lattice 函数中数据点的颜色。这个想法是响应可能是一个或两个因素的函数。数据点的颜色应由fac1 确定。这是函数:

compareCats <-
function(formula = NULL, data = NULL, cols = NULL, ...) {

    TwoFac <- FALSE
    res <- as.character(formula[[2]])
    if (length(formula[[3]]) == 1) {
        fac1 <- as.character(formula[[3]])
        }
    if (length(formula[[3]]) == 3) {
        fac2 <- as.character(formula[[3]][3])
        fac1 <- as.character(formula[[3]][2])
        TwoFac <- TRUE
        }

    args <- as.list(match.call(expand.dots = FALSE)[-1]) # used a bit later

    if (TwoFac) keep <- c(res, fac1, fac2) # Reduce the df and clean it of NAs
    if (!TwoFac) keep <- c(res, fac1)
    data <- data[, keep]
    data <- na.omit(data)

    # cols2 is used for the data points according to levels in fac1
    if (!TwoFac) cols2 <- cols[data[,fac1]] # works fine
    if (TwoFac) {
        # In this case, the points and panels are drawn in an order I don't understand
        cols2 <- rep(NA_character_, nrow(data))
        for (i in 1:nlevels(data[,fac1])) { # make the colors correspond to the original order
            tmp <- which(data[,fac1] == levels(data[,fac1])[i])
            cols2[tmp] <- cols[i]
            }
        }
    data$cols <- cols2

    p <- lattice::xyplot(as.formula(args$formula), # now the plot
        data = eval(args$data), ...,
        panel = function(x, y, ...) {
            lattice::panel.xyplot(x, y, col = data$cols, ...)
            }
            )
    return(p)   
    }

这里是数据和两个函数调用:

set.seed(13)
mydf <- data.frame(
resp = rnorm(40),
cat1 = sample(LETTERS[1:3], 40, replace = TRUE),
cat2 = sample(letters[1:2], 40, replace = TRUE))
library("lattice")
library("plyr")
# One factor / works fine
p <- compareCats(formula = resp~cat1, data = mydf,
cols = c("red", "orange", "blue"))
print(p)
# Two factors / colors not assigned correctly
p <- compareCats(formula = resp~cat1 | cat2, data = mydf,
cols = c("red", "orange", "blue"))
print(p)

第一个生成这个图表: 第二个这个: 如何使第二个示例中的颜色从左到右为红色、橙色、蓝色、红色、橙色、蓝色?我尝试了很多方法,有时可以让第一个面板表现出来,但第二个面板似乎是随机的。显然,我不太清楚 Lattice 在 2 因素情况下使用什么顺序,文档建议使用交互,但这仍然留下了几种可能性,我都无法弄清楚。

【问题讨论】:

    标签: r lattice


    【解决方案1】:

    如果您想在面板中一致地更改点的颜色,我建议您通过更标准的 groups= 参数来实现。我会在您的 compareCats 函数中更改这两行

    cols2 <- factor(cols2, levels=cols) # no need to attach to data
    p <- lattice::xyplot(as.formula(args$formula), groups=cols2,
        data = eval(args$data), ...,
        par.settings=list(superpose.symbol=list(col=cols))
    )
    

    这里我们使用groups= 将一个点分配给不同的组,我们使用 superpose.symbol 指定分配给每个组的颜色。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 2018-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      相关资源
      最近更新 更多