I have a data.frame with 72 discrete categories. When I colour by these categories I get 72 different keys in the legend. I would prefer to only use every 2nd or 3rd key.
Any idea how I cut down on the number of lines in the legend?
Thanks H.
Code that reproduces my problem is given 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()
You can treat your period
values as numeric in geom_point()
. That will make colors as gradient (values from 1 to 72 corresponding to number of levels). Then with scale_colour_gradient()
you can set number of breaks 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)])
It looks hard to customize the legend here for a discrete_color_scale!So I propose a lattice solution. You need just to give the right text to 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,...)
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.