Reputation: 24898
I often visualize one time series against another using scatterplots in Excel, but since recent data are more relavant, I use different highlights for more recent time periods:
In this case the month, week and today plots are simply different (more recent) slices of the same time series, so basically there are four superimposed plots in this chart. How can I do the same in R? I have gotten so far:
But i'd like to replicate what I have in excel. How do I add new plots to the same chart in R?
Or perhaps I could even go further and use the col attribute in the R plot to get a continuous increase in the colour up to the today value, thus avoiding these discreet steps? How would I do that?
Upvotes: 4
Views: 10681
Reputation: 47541
You can use the lower level plotting function points()
to add points to an already existing plot. It works in exactly the same way you create a scatter plot through plot()
except that it adds points to the currently used plot.
For example:
plot(1:10)
points(10:1,col="red")
One way to do the colors is by using rgb()
as Chi suggested. I like to create a dummy variable with values between 0 and 1 and use that as a scalar on the colors. For example:
x <- rnorm(100)
y <- 0.5*x + rnorm(100)
z <- 0.5*y + rnorm(100)
dum <- (z - min(z)) / (max(z) - min(z))
plot(x,y,col=rgb(1-dum*0.4,1-dum*0.8,1-dum*0.8),pch=16)
This makes the points redder as they have a higher value of z
. Of course you can change min(z)
and max(z)
into the bounds of the scale you are interested in.
Upvotes: 7
Reputation: 179408
Here is a skeleton example of how to go about doing it using ggplot
:
library(ggplot2)
day <- 1:100
dat <- data.frame(
day=day,
x = day+(1+rnorm(100, 0, 10)),
y = 5 + day+(1+rnorm(100, 0, 10)),
when = cut(day, 5)
)
ggplot(dat, aes(x=x, y=y, colour=when)) + geom_point()
And for smooth colours:
ggplot(dat, aes(x=x, y=y, colour=day)) + geom_point() +
scale_colour_gradient(low="pink", high="red")
Upvotes: 5