ggplot,facets和系列中的颜色变化

时间:2012-08-14 20:37:27

标签: r ggplot2 reshape2

我的传感器数据看起来像这样:

tm <- seq(1,17)
chg <-    c(13.6,13.7,13.8,13.9,14.1,14.2,14.4,14.6,14.7,14.9,14.9,15.0,15.0,13.7,13.7,13.6,13.7)
batt_A <- c(   1,   1,   1,   1,   1,   1,   1,   1,   1,   2,   2,   2,   2,   3,   3,   0,   0)
batt_B <- c(   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   1,   1)
bus    <- c(12.4,12.5,12.4,11.7,11.6,12.2,12.4,11.8,11.7,11.5,12.1,12.0,11.6,11.5,11.4,12.6,12.5)
pwr <- data.frame(tm,batt_A,batt_B,chg,bus)

我想在单独的构面板中创建两个线图(chg和总线对抗tm)。扭曲的是,我还希望每条线都有颜色,以表示它正在跟踪哪个电池。因此,如果batt_A> 0,它正在充电,我希望充电线为绿色;如果batt_A == 0,它就在公交车上,我希望公交线路是绿色的。对于batt_B也是如此,除了线条是蓝色(或任何颜色)。

我得到了熔化+刻面组合,但是如何添加颜色?

(ps:我正在使用分面,因为还有6个传感器在同一时间尺度上变化,我想全部观察它们)

根据Andrie在下面的回答,我得到了这个解决方案,但重新编码很可怕:

mpwr <- melt(pwr, id.vars=1:3)

mpwr$batt <- ''
mpwr$batt <- ifelse(mpwr$batt_A>0 & mpwr$variable=="chg", "A", mpwr$batt)
mpwr$batt <- ifelse(mpwr$batt_B>0 & mpwr$variable=="chg", "B", mpwr$batt)
mpwr$batt <- ifelse(mpwr$batt_A==0 & mpwr$variable=="bus", "A", mpwr$batt)
mpwr$batt <- ifelse(mpwr$batt_B==0 & mpwr$variable=="bus", "B", mpwr$batt)
mpwr$batt <- as.factor(mpwr$batt)

ggplot(mpwr, aes(x=tm, group=1)) + 
   geom_line(aes(y=value, colour=batt)) +
   geom_line(aes(y=value, colour=batt)) +
   facet_grid(~variable) +
   scale_colour_discrete("Charging")

数据处理可以清理,但我想我就在那里!

1 个答案:

答案 0 :(得分:4)

如下所示:

library(reshape2)
library(ggplot2)

mpwr <- melt(pwr, id.vars=1:3)

ggplot(mpwr, aes(x=tm, group=1)) + 
  geom_line(aes(y=value, colour=factor(batt_A!=0))) +
  geom_line(aes(y=value, colour=factor(batt_B!=0))) +
  facet_grid(~variable) +
  scale_colour_discrete("Charging")

enter image description here

相关问题