Skip to content

Instantly share code, notes, and snippets.

@lawsofthought
Last active March 30, 2016 20:01
Show Gist options
  • Save lawsofthought/0e515fb14461534477cf5e585672e95c to your computer and use it in GitHub Desktop.
Save lawsofthought/0e515fb14461534477cf5e585672e95c to your computer and use it in GitHub Desktop.
An R function to create a plot with side by side panels of different colors and a random walk line plot on top.
####################################
example.colors <- c('cyan',
'darkgoldenrod',
'cornflowerblue',
'chocolate1',
'chartreuse1')
myplot <- function(N, example.colors, drift=0.1, switch.p=0.01){
K <- length(example.colors)
# Generate random data
# X is a random walk
# Y is a sequence of integers 1, 2 ... K
# The values of Y switch from one time point to the next with prob=0.01
X <- rep(0, N)
Y <- rep(0, N)
x <- 0
y <- sample(1:K, size=1)
for (i in seq(N)){
x <- rnorm(1, mean=x, sd=drift)
X[i] <- x
if (runif(1) < switch.p) {
y <- sample(1:K, size=1)
}
Y[i] <- y
}
### Set up a blank plot
d <- max(X)-min(X)
a <- min(X) - 0.05 * d
b <- min(X) + 1.05 * d
plot(1,
type='n',
xlim=c(1, N),
ylim=c(a, b),
ylab='x(t)',
xlab='time')
### Plot the backgrounds
for (i in seq(1:N)){
polygon(c(i-1, i-1, i, i),
c(a, b, a, b),
col=example.colors[Y[i]],
border=NA)
}
# Plot a line plot on top of the colors
lines(X)
}
myplot(1000, example.colors)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment