Scale colour legend

765 views Asked by At

can someone help to change the legend of this graphic to a continuous colour legend, like the legend in the second image.

library(demography)

plot.demogdata(portugal,series='male')   
legend("bottomright",legend=unique(portugal$year),
  col=rainbow(length(portugal$year)*1.25), ncol=5, pch=19, 
  title="Year", cex=0.5)

enter image description here

enter image description here

1

There are 1 answers

2
Petr Matousu On

Try this. Not hi-tech, but works well for your need and does not require extra packages. Copy & paste to R console to see how it works.

# not using layout function

# colors
n <- 1:50
col <- rainbow(length(n))

# expanding right margin 
par(mar=c(5,4,4,8),xpd=T)

# simulating any graph
plot(n,n*2,type='n',ylab="fun(x,n)")

# making DYI scale and legend
# scale
x <- rep(par('usr')[2]*1.1,length(n)+1)
y <- seq(f=par('usr')[3],t=par('usr')[4],length.out=length(n)+1)
nul <- sapply(n,FUN=function(n,col,x,y,...){lines(x=x[c(n,n+1)],y=y[c(n,n+1)],col=col[n],...)},lwd=30,lend="butt",col=col,x=x,y=y)
# labels
ty <- y[n]+diff(y)/2
tx <- rep(par('usr')[2]*1.25,length(n))
t <- paste("Lab",n)
ti <- pretty(n)
text(x=tx[ti],y=ty[ti],t[ti])