[R] consolidate legends in ggplot2

Engelmann, Bernd Bernd.Engelmann at amd.com
Thu Feb 7 15:42:36 CET 2008


Thank you, Hadley,

the real example needs scales with more breaks, this is the only
difference.

The script overwrites the original ggplot2 code with the code below to
achive this. 
This was hardcoded for the special case.

Can ggplot2 handle bigger numbers of breaks by reusing aesthetics ?

Bernd


ScaleMy <- proto(ScaleColour, expr={

	new <- function(., name=NULL, palette=1, type="qual", alpha=1,
variable) {
		proto(., name=name, palette=palette, type=type,
.input=variable, .output=variable, .alpha=alpha)
	}
	
  colors <-
c('green','red','blue','violet','orange2','skyblue','magenta','burlywood
1',
 
'cadetblue1','maroon3','aquamarine','bisque1','darkgoldenrod1','darkkhak
i','cornsilk3',
  'lightsalmon1','deepskyblue2','goldenrod1','hotpink','lightslateblue',
  'mistyrose1','olivedrab1','plum1','pink1','orange3')

	breaks <- function(.) {
		n <- length(.$domain())
		alpha(.$colors[1:n
    
    ], .$.alpha)
	}

	
	max_levels <- function(.) length(.$colors)


})

scale_colour_My <- function(...) ScaleMy$new(..., variable = "colour")


Scales$guide_legend <- function(.) {
		legs <- compact(lapply(.$.scales, function(x)
x$guide_legend()))
		legs[sapply(legs, length) == 0] <- NULL
		legs
	}

ScaleShape$breaks <- function(.) {
		(if (.$solid) {
			c(16, 17, 15, 3, 7, 8, 16, 17, 15, 3, 7, 8, 16,
17, 15, 3, 7, 8)
		} else {
			c(1, 2, 0, 3, 7, 8, 1, 2, 0, 3, 7, 8, 1, 2, 0,
3, 7, 8)
		})[1:length(.$domain())]
	}

ScaleShape$max_levels <- function(.) 18

 

-----Original Message-----
From: hadley wickham [mailto:h.wickham at gmail.com] 
Sent: Thursday, February 07, 2008 3:11 PM
To: Engelmann, Bernd
Cc: r-help at r-project.org
Subject: Re: [R] consolidate legends in ggplot2

On Feb 7, 2008 3:43 AM, Engelmann, Bernd <Bernd.Engelmann at amd.com>
wrote:
> Hello,
>
> the same parameter for colour and shape aesthetics gives 2 legends:
>
> library(ggplot2)
> p <- ggplot(mtcars, aes(x=wt, y=mpg))
> p + geom_point(aes(colour=factor(cyl), shape=factor(cyl)))
>
> Can the 2 legends be consolidated to one with colours and shapes of 
> the symbols matched between legend and plot ?

Not in the current version of ggplot2, but I'm working on that code in
the development version at the moment and it will be included in the
next version.  If your real example is more complicated than that,
please let me know so that I can check if my code works.

Hadley

--
http://had.co.nz/



More information about the R-help mailing list