如何在lattice包绘图时在strip中使用表达式,例如$x^2$之类的文字

如何在lattice包绘图时在strip中使用表达式,例如x2之类的文字。

示例数据是iris数据,并且添加了新的一列cond2:

library(lattice)
df <- cbind(iris, cond2 = c('a', 'b'))
head(df)

##   Sepal.Length Sepal.Width Petal.Length Petal.Width Species cond2
## 1          5.1         3.5          1.4         0.2  setosa     a
## 2          4.9         3.0          1.4         0.2  setosa     b
## 3          4.7         3.2          1.3         0.2  setosa     a
## 4          4.6         3.1          1.5         0.2  setosa     b
## 5          5.0         3.6          1.4         0.2  setosa     a
## 6          5.4         3.9          1.7         0.4  setosa     b

head(df$Species)

## [1] setosa setosa setosa setosa setosa setosa
## Levels: setosa versicolor virginica

head(df$cond2)

## [1] a b a b a b
## Levels: a b

定义新的strip函数,在其中重新设置因子水平为表达式类型:

strip.func <- function (which.given, factor.levels, ...) {
    if (which.given == 1) {
       cat('Now the input factor.levels is :')
       print(factor.levels)
       factor.levels <- expression('S'^1,'S'^3,'S'^4)
    } else if (which.given == 2) {
       cat('Now the input factor.levels is :')
       print(factor.levels)
       factor.levels <- expression('Cond'[a],'Cond'[b])
    }
    strip.default(which.given, factor.levels, ...)
}

最后画图,将strip参数设置为上面的函数:

xyplot(Sepal.Length ~ Sepal.Width | Species * cond2, 
       data = df,
       strip = strip.func,
       par.settings = list(layout.heights = list(strip = 1.5)))

如何在lattice包绘图时在strip中使用表达式,例如$x^2$之类的文字_第1张图片

## Now the input factor.levels is :[1] "setosa"     "versicolor" "virginica" 
## Now the input factor.levels is :[1] "a" "b"
## Now the input factor.levels is :[1] "setosa"     "versicolor" "virginica" 
## Now the input factor.levels is :[1] "a" "b"
## Now the input factor.levels is :[1] "setosa"     "versicolor" "virginica" 
## Now the input factor.levels is :[1] "a" "b"
## Now the input factor.levels is :[1] "setosa"     "versicolor" "virginica" 
## Now the input factor.levels is :[1] "a" "b"
## Now the input factor.levels is :[1] "setosa"     "versicolor" "virginica" 
## Now the input factor.levels is :[1] "a" "b"
## Now the input factor.levels is :[1] "setosa"     "versicolor" "virginica" 
## Now the input factor.levels is :[1] "a" "b"

你可能感兴趣的:(R语言,lattice)