Marcos Alex
Marcos Alex

Reputation: 1630

adding color bar in a simple line plot with defined rainbow colors in R

I want to make a line plot with several lines, whereby each line corresponds to a defined color. Then I want to show the color bar aside the plot. It is straightforward to define and plot the lines (as a simple example below), but I could not put the bar plot ( I have tried different approaches). Notice: I dont want to use ggplot2.

n =30
color=rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha = 1)
x=seq(1:10) 
plot(x,1*x,col=color[1],type="l")
for (i in seq(2,30)){
  lines(x,i*x,col=color[i])}

Upvotes: 0

Views: 3764

Answers (1)

jlhoward
jlhoward

Reputation: 59385

This is a perfect example of why ggplot is so popular... AFAIK, drawing a colorbar legend in base R graphics requires creating a layout with two columns, and putting an image(...) in the second slot, as in:

n =30
color=rainbow(n, s = 1, v = 1, start = 0, end = max(1, n - 1)/n, alpha = 1)
layout(t(1:2),widths=c(6,1))
x=0:10
par(mar=c(4,4,1,0.5))
plot(x,1*x,col=color[1],type="l")
for (i in seq(2,30)){
  lines(x,i*x,col=color[i])}
par(mar=c(5,1,5,2.5))
image(y=2:30,z=t(2:30), col=color[2:30], axes=FALSE, main="Slope", cex.main=.8)
axis(4,cex.axis=0.8,mgp=c(0,.5,0))

For information on all those obscure plot parameters (mar, mgp, cex.main, etc., .etc), type ?par. Also, there are also several packages that try to make this easier: here, and here

And, even though you didn't ask for it, a ggplot solution.

library(ggplot2)
n <- 30
df   <- expand.grid(x=0:10,slope=2:n)
df$y <- with(df,x*slope)
ggplot(df) + geom_line(aes(x,y,group=slope,color=slope))+
  coord_cartesian(ylim=c(0,10))+
  scale_color_gradientn(colours=rainbow(n))+
  theme_bw()

Upvotes: 4

Related Questions