Tuesday 15 February 2011

r - how to format multiple labels into a single legend in ggplot2 -



r - how to format multiple labels into a single legend in ggplot2 -

i cannot seem find solution specific problem, hope can help (and haven't missed something).

i have info in long format ggplot2 2 attributes set label in legend. sample dataset:

require(ggplot2) ds1=data.frame("heading"="alpha","val"=0.534,"x"=seq(1,5,1),"y"=(seq(10,2,-2)**1.5)) ds2=data.frame("heading"="beta","val"=0.732,"x"=seq(1,5,1),"y"=seq(30,6,-6)) ds3=data.frame("heading"="carotene","val"=0.877,"x"=seq(1,5,1),"y"=seq(3,15,3)) test1=rbind(ds1,ds2,ds3) test1$head1=factor(test1$heading) test1$val=factor(test1$val) p5=ggplot(test1,mapping=aes(x=x,y=y,colour=heading)) + geom_line(size=1) print(p5)

that sec piece of data, however, val, legend. suggestion found here used interaction:

p5 = ggplot(test1,mapping=aes(x=x,y=y,colour=interaction(heading,val,sep=" "))) + geom_line(size=1) + labs(colour="heading")

which has info wanted, run together. alternatively, tried

p5=ggplot(test1,mapping=aes(x=x,y=y,colour=heading)) + geom_line(size=1) p5 + scale_colour_discrete(labels=paste(levels(test1$heading)," (",levels(test1$val),")",sep=""))

however aiming, "val" info formatted such appropriate number of spaces inserted separate them columns. data.frame, legend/colour info plot well. or somehow right-justify half (val) leaving first half of each line (heading) left justified. trying,

p5 = ggplot(test1,mapping=aes(x=x,y=y,colour=interaction(heading,val,sep="\t"))) + geom_line(size=1) + labs(colour="heading")

to forcefulness tab stop (hoping might work in machine-dependent manner), not seem work either, although using "\n" (for space , clarity, maintain labels on 1 line, since there 12 levels in info plotting , viewer able scan downwards range of values easily). suggestions...

if you're comfortable reversing value & label, give columns seek:

test1$grouping <- sprintf("%s - %s", test1$val, test1$heading) ggplot(test1,mapping=aes(x=x,y=y,colour=grouping)) + geom_line(size=1) + labs(colour="heading")

r ggplot2 legend

No comments:

Post a Comment