连接一组的线,另一组的颜色

时间:2013-01-31 02:43:19

标签: r lattice

我的数据以两个变量为条件,一个主要条件,一个次要条件。我希望xyplotlattice)在一个面板中包含点和线(type='b'),以便主要条件决定颜色,次要条件用于绘制线条。 / p>

这是一个代表我的问题的例子(参见下面的代码来生成数据框)。 d是主要条件,c是次要条件。

> dat
     x          y c d
1    1  0.9645269 a A
2    2  1.4892217 a A
3    3  1.4848654 a A
....
10  10  2.4802803 a A
11   1  1.5606218 b A
12   2  1.5346806 b A
....
98   8  2.0381943 j B
99   9  2.0826099 j B
100 10  2.2799917 j B

c上设置连接线的方法是在图中使用groups=c。然后告诉他们不同的方法是使用以d

为条件的公式
xyplot(y~x|d, data=dat, type='b', groups=c)

enter image description here

但是,我想在同一个面板中绘制这些图。删除d上的公式条件会产生一个面板,但是当指定group=d时,会有"回扫"画线:

xyplot(y~x, data=dat, type='b', groups=d, auto.key=list(space='inside'))

enter image description here

我想要的看起来非常像上面的情节,只有没有这些"回扫"线。

在此示例中可以明确设置颜色,因为我知道有五行类别' A'其次是五个类别' B'但这对我真正的问题不会轻易解决。此外,auto.key在以这种方式设置颜色时毫无用处:

xyplot(y~x, data=dat, type='b', groups=c, col=rep(5:6, each=5))

enter image description here

数据:

set.seed(1)
dat <- do.call(
  rbind,
  lapply(1:10,
         function(x) {
           firsthalf <- x < 6
           data.frame(x=1:10, y=log(1:10 + rnorm(10, .25) + 2 * firsthalf),
                                c=letters[x],
                                d=LETTERS[2-firsthalf]
                                )
         }
  )
)

2 个答案:

答案 0 :(得分:3)

默认图形参数来自superpose.symbolsuperpose.line。一种解决方案是使用par.settings参数设置它们。

## I compute the color by group 
col <-by(dat,dat$c,
                FUN=function(x){
                  v <- ifelse(x$d=='A','darkgreen','orange')
                  v[1]  ## I return one parameter , since I need one color
                  }
         )

 xyplot(y~x, data=dat, type='b', groups=c,
       auto.key = list(text =levels(dat$d),points=F),
       par.settings=
         list(superpose.line   = list(col = col),                 ## color of lines
              superpose.symbol = list(col=col),                   ## colors of points
              add.text = list(col=c('darkgreen','orange'))))      ## color of text in the legend

enter image description here

答案 1 :(得分:1)

它必须是格子吗?在ggplot中它很容易:

library(ggplot2)

ggplot(dat, aes(x=x,y=y,colour=d)) + geom_line(aes(group=c),size=0.8) + geom_point(shape=1) 

这是一个快速而肮脏的例子。您可以自定义线条的颜色,图例,轴,背景......

enter image description here