Multiple colours on the same line, with certain differentiating parameters

171 views
Skip to first unread message

Vimal B

unread,
Sep 13, 2009, 2:08:05 PM9/13/09
to ggplot2
Hello,

I have some normal plot codes to run a graph where certain portions of a particular data series can be highlighted in different colours. I was wondering whether this could be done in ggplot2. This is what I tried:

b<-cumsum(rnorm(1000))
x<-sample(c(1,2), size=1000, replace=TRUE)
y<-sample(c(1,2), size=1000, replace=TRUE)

T<-length(b)
t<-1:(T)

par(mfrow=c(1,2))
plot(t, b, type="n", ax=FALSE, ylab="",xlab="",col=x, ylim=range(b))
title("x")
segments(t,b[t],t+1,b[t+1],col=y)

plot(t, b, type="n", ax=FALSE, ylab="",xlab="",col=x)
title("y")
legend("topleft", legend=c("low","high"), pch=2, col=1:2, merge=FALSE, title="regime", lty=1, bg="white")
segments(t,b[t],t+1,b[t+1],col=x)

library(ggplot2)
tmp <- data.frame(cbind(t,b,x,y))
ggplot(tmp, aes(t))+geom_line(aes(y=b,colour=factor(x)))+labs(x=NULL,y=NULL)

The problem is that I cannot hide those parts of the line that I do not want visible in ggplot, which I could to with the normal plot command.

Am I missing something very obvious?

Regards,
Vimal




baptiste auguie

unread,
Sep 13, 2009, 2:56:09 PM9/13/09
to Vimal B, ggplot2
Hi,

Does this produce what you want?

library(ggplot2)
tmp <- melt(data.frame(cbind(t,b,x,y)),meas=c("x","y"))
head(tmp)

ggplot(tmp, aes(x=t,y=b,groups=variable)) +
facet_wrap(~variable) +
geom_path(aes(y=b,colour=factor(value))) +
labs(x=NULL,y=NULL)


HTH,

baptiste
--
_____________________________

Baptiste Auguié

School of Physics
University of Exeter
Stocker Road,
Exeter, Devon,
EX4 4QL, UK

http://newton.ex.ac.uk/research/emag
______________________________

Vimal B

unread,
Sep 13, 2009, 3:11:05 PM9/13/09
to baptiste auguie, ggplot2
Thanks for the quick response Babtiste! It works.


Regards,
Vimal



2009/9/14 baptiste auguie <bapt...@googlemail.com>
Reply all
Reply to author
Forward
0 new messages