Ggplot2: use each key label of the Nth label

I have data.frame with 72 discrete categories. When I color these categories, I get 72 different keys in the legend. I would prefer to use only every second or third key.

Any idea how I reduce the number of lines in a legend?

Thanks N.

The code that reproduces my problem is below.

t=seq(0,2*pi,length.out=10) RR=rep(cos(t),72)+0.1*rnorm(720) dim(RR)=c(10,72) stuff=data.frame(alt,RR) names(stuff)=c("altitude", paste(rep(15:20,each=12), rep(c("00","05",as.character(seq(from=10,to=55,by=5))),6), sep=":")) bb=melt(stuff,id.vars=c(1)) names(bb)[2:3]=c("period","velocity") ggplot(data=bb,aes(altitude,velocity))+geom_point(aes(color=period))+geom_smooth() 
+4
source share
2 answers

You can consider your period values ​​as numeric in geom_point() . This will make the colors a gradient (values ​​from 1 to 72, corresponding to the number of levels). Then using scale_colour_gradient() you can set the number of gaps you need and add labels as your actual period values.

 ggplot(data=bb,aes(altitude,velocity))+ geom_point(aes(color=as.numeric(period)))+ geom_smooth()+ scale_colour_gradient("Period",low="red", high="blue", breaks=c(seq(1,72,12),72),labels=unique(bb$period)[c(seq(1,72,12),72)]) 

enter image description here

+3
source

It's hard for me to set up a legend here for discrete_color_scale! Therefore, I propose a lattice solution. You just need to specify the correct text in the auto.key list.

 libarry(latticeExtra) labels.time <- unique(bb$period)[rep(c(F,F,T),each=3)] ## recycling here to get third label g <- xyplot(velocity~altitude, data=bb,groups=period, auto.key=list(text=as.character(labels.time), columns=length(labels.time)/3), par.settings = ggplot2like(), axis = axis.grid, panel = function(x,y,...){ panel.xyplot(x,y,...) panel.smoother(x,y,...) }) 

enter image description here

+1
source

All Articles