Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I plot more than one series in the same R scatterplot?

Tags:

r

charts

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:

enter image description here

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:

enter image description here

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?

like image 237
Thomas Browne Avatar asked Dec 17 '22 13:12

Thomas Browne


1 Answers

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

Edit:

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.

enter image description here

like image 137
Sacha Epskamp Avatar answered Jan 30 '23 23:01

Sacha Epskamp