-2

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

Spacedman
  • 92,590
  • 12
  • 140
  • 224
user2898085
  • 49
  • 2
  • 4
  • 14
  • 2
    The lower graph was produced with ggplot2. You can easily make the upper graph with ggplot2 and will get a continuous colour scale automatically. – Roland Dec 18 '13 at 10:31
  • 2
    How do you derive the object `portugal`? Without this we can't reproduce your problem. – SlowLearner Dec 18 '13 at 12:15
  • Not really easy using base plot. Hints : you should prepare the legend region using `layout` and then use `image` and `axis`. As already mentioned Easier here to use some higher plot style.(ggplot2/lattice) – agstudy Dec 18 '13 at 14:18
  • portugal is demogdata portugal<-hmd.mx("PRT",-,-) – user2898085 Dec 18 '13 at 15:30

1 Answers1

1

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])
Petr Matousu
  • 3,120
  • 1
  • 20
  • 32
  • when I run the instruction plot(n,n*2,type='n',ylab="fun(x,n)") the plot is clear. – user2898085 Dec 19 '13 at 12:45
  • @user2898085 yes, that is because my code is just example, if you want to use it in your case, you have to adjust the code to your needs, I have old R version, no chance to install the package you are using, so I helped myself with epty plot. – Petr Matousu Dec 19 '13 at 13:10