[R] ggplot2: Legend title

Brian Diggs diggsb at ohsu.edu
Fri Apr 20 23:08:56 CEST 2012


On 4/20/2012 12:11 PM, Bush, Daniel P. DPI wrote:
> I'm designing a set of plots intended for a general audience; here's
> the code for one of them, using the latest version of ggplot:
>
> plot.enr.all<-
>    ggplot(data=df1, aes(x=HS_GRAD_YEAR, y=Percentage, group=Enrolled_by,
>                         color=Enrolled_by, shape=Enrolled_by, fill=Enrolled_by)) +
>    geom_line() + geom_point(size=3.5) +
>    scale_y_continuous(breaks=seq(0, 100, 10), limits=c(0, 100),
>                       labels=paste(seq(0, 100, 10), "%", sep="")) +
>    scale_color_manual(values=c("orange", "red"),
>                       breaks=c("PCT_ENR_FALL1", "PCT_ENR_FALL2"),
>                       labels=c("1st fall", "2nd fall")) +
>    scale_fill_manual(values=c("orange", "red"),
>                      breaks=c("PCT_ENR_FALL1", "PCT_ENR_FALL2"),
>                      labels=c("1st fall", "2nd fall")) +
>    scale_shape_manual(values=c(21, 22),
>                       breaks=c("PCT_ENR_FALL1", "PCT_ENR_FALL2"),
>                       labels=c("1st fall", "2nd fall")) +
>    opts(title="Postsecondary Enrollment Rates of High School Graduates",
>         legend.position="bottom", axis.title.y=theme_blank()) +
>    guides(fill=guide_legend(nrow=1)) + xlab("Graduation year")
>
> The legend on the resulting plot uses "Enrolled_by" for a title. I'd
> like it to be able to use "Enrolled by" without the underscore, but
> thus far I've been unable to get ggplot to use a variable name
> containing a space. Is there a straightforward way of doing so?

Easier than changing the variable name, change the legend title itself. 
This is the name argument, which needs to be passed to all of color, 
fill, and shape:

...
   scale_color_manual(name="Enrolled by",
                      values=c("orange", "red"),
                      breaks=c("PCT_ENR_FALL1", "PCT_ENR_FALL2"),
                      labels=c("1st fall", "2nd fall")) +
   scale_fill_manual(name="Enrolled by",
                     values=c("orange", "red"),
                     breaks=c("PCT_ENR_FALL1", "PCT_ENR_FALL2"),
                     labels=c("1st fall", "2nd fall")) +
   scale_shape_manual(name="Enrolled by",
                      values=c(21, 22),
                      breaks=c("PCT_ENR_FALL1", "PCT_ENR_FALL2"),
                      labels=c("1st fall", "2nd fall")) +
...


> DB
>
> Daniel Bush
> Educational Measurement Consultant
> Office of Educational Accountability
> Wisconsin Department of Public Instruction
> PO Box 7841 | Madison, WI 53707-7841
> daniel.bush -at- dpi.wi.gov | www.dpi.wi.gov/oea/
> Ph: 608-264-9321 | Fax: 608-266-8770
>
>
> 	[[alternative HTML version deleted]]
>


-- 
Brian S. Diggs, PhD
Senior Research Associate, Department of Surgery
Oregon Health & Science University



More information about the R-help mailing list