Question

I've got sensor data that looks like this:

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)

I want to create two line graphs (chg and bus against tm) in separate facet panels. The twist is that I want also to have each line colored to represent which battery it's tracking. So if batt_A>0, it's charging and I want the charge line to be green; and if batt_A==0, it's on the bus, and I want the bus line to be green. Same for batt_B, except the lines would be blue (or whatever color).

I get the melt + facet combination, but how to add the coloring?

(ps: I'm using facets because there are 6 more sensors varying on the same timescale and I want to watch them all)

With Andrie's answer below, I got to this solution, but the recode is horrible:

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")

The data processing could be cleaned up, but I think I'm there!

Was it helpful?

Solution

Something like the following:

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top