Italics on some of the legend labels

3,510 views
Skip to first unread message

Luciano Selzer

unread,
Mar 9, 2010, 8:45:52 AM3/9/10
to ggplot2
Hi Group, I wanted to know if it's possible to make some of the labels of the legend have italic while the others have the normal font. Something like the code below, except it doesn't work. Is it possible to do this? If so, how?
Thank you
dsamp <- diamonds[sample(nrow(diamonds), 1000), ] 
d <- qplot(carat, price, data=dsamp, colour=clarity)
lab <- levels(dsamp$clarity)
lab_italics <- c(expression(italic("Text1")), expression(italic("Text2")), lab[3:length(lab)])
d + scale_colour_hue(breaks=lab, labels=lab_italics)




Luciano

baptiste auguie

unread,
Mar 9, 2010, 10:42:23 AM3/9/10
to Luciano Selzer, ggplot2
Hi,

For a reason that is just not clear to me the following works,

l1 <- expression(italic("Text1"), italic("Text2"), lab[3], lab[4],
lab[5], lab[6], lab[7], lab[8])

d + scale_colour_hue(breaks=lab, labels=l1)

while a seemingly similar expression does not,

l1 <- as.expression(do.call(c, list(expression(italic("Text1"),
italic("Text2")), lab[3:length(lab)])))

I hope R help gurus could explain that one.

Best,

baptiste

> --
> You received this message because you are subscribed to the ggplot2 mailing
> list.
> To post to this group, send email to ggp...@googlegroups.com
> To unsubscribe from this group, send email to
> ggplot2+u...@googlegroups.com
> For more options, visit this group at
> http://groups.google.com/group/ggplot2

baptiste auguie

unread,
Mar 9, 2010, 10:54:30 AM3/9/10
to Luciano Selzer, ggplot2
Whoops, the first one doesn't even work properly. Sorry for the noise.

baptiste

takahashi kohske

unread,
Mar 9, 2010, 1:07:09 PM3/9/10
to Luciano Selzer, ggplot2
Hi,

easy workaround is using plain annotation for the other labels instead
of simple text:

d + scale_colour_hue(breaks=lab,
labels=parse(text=c(paste('italic(',lab[1:3],')'),
paste('plain(',lab[-c(1:3)],')'))))

it does works in my test.


But I could not find out what the following code actually does in
build_legend, which induced the error when the labels includes some
(but not all) expression:

numeric_labels <- all(sapply(mapping$.label, is.language)) ||
suppressWarnings(all(!is.na(sapply(mapping$.label, "as.numeric"))))
hpos <- numeric_labels * 1

the first all() returns FALSE because some of labels are character,
and then as.numeric() induces error because the other of labels are
expression.


2010/3/9 Luciano Selzer <luciano...@gmail.com>:

Hadley Wickham

unread,
Mar 9, 2010, 3:36:28 PM3/9/10
to takahashi kohske, Luciano Selzer, ggplot2
That code tries to figure out whether to right or left align the
labels. I never considered the case of mixed text and expressions.

Hadley

--
Assistant Professor / Dobelman Family Junior Chair
Department of Statistics / Rice University
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages