Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use subscripts in ggplot2 legends [R]

Tags:

r

ggplot2

Can I use subscripts in ggplot2 legends? I see this question on greek letters in legends and elsewhere, but I can't figure out how to adapt it.

I thought that using expression(), which works in axis labels, would do the trick. But my attempt below fails. Thanks!

library(ggplot2)
temp <- data.frame(a = rep(1:4, each = 100), b = rnorm(4 * 100), c = 1 + rnorm(4 * 100))
names(temp)[2:3] <- c("expression(b[1])", "expression(c[1])")
temp.m <- melt(temp, id.vars = "a")
ggplot(temp.m, aes(x = value, linetype = variable)) + geom_density() + facet_wrap(~ a)
like image 389
Richard Herron Avatar asked Jun 01 '11 14:06

Richard Herron


People also ask

How do you superscript in ggplot2?

To add superscript as a title add bquote function with value inside ggtitle().

How do you do a subscript in R?

Subscripts and Superscripts To indicate a subscript, use the underscore _ character. To indicate a superscript, use a single caret character ^ . Note: this can be confusing, because the R Markdown language delimits superscripts with two carets.

How do you use superscript in R?

Superscript is “started” by the caret ^ character. Anything after ^ is superscript. The superscript continues until you use a * or ~ character. If you want more text as superscript, then enclose it in quotes.

How do I change the legend text in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


2 Answers

The following should work (remove your line with names(temp) <-...):

ggplot(temp.m, aes(x = value, linetype = variable)) + 
  geom_density() + facet_wrap(~ a) +    
  scale_linetype_discrete(breaks=levels(temp.m$variable),
                          labels=c(expression(b[1]), expression(c[1])))

See help(scale_linetype_discrete) for available customization (e.g. legend title via name=).

like image 172
chl Avatar answered Oct 11 '22 01:10

chl


If you want to incorporate Greek symbols etc. into the major tick labels, use an unevaluated expression.

For a bar graph, i did the following:

library(ggplot2)
data <- data.frame(names=tolower(LETTERS[1:4]),mean_p=runif(4))

p <- ggplot(data,aes(x=names,y=mean_p))
p <- p + geom_bar(colour="black",fill="white")
p <- p + xlab("expressions") + scale_y_continuous(expression(paste("Wacky Data")))
p <- p + scale_x_discrete(labels=c(a=expression(paste(Delta^2)),
                               b=expression(paste(q^n)),
                               c=expression(log(z)),
                               d=expression(paste(omega / (x + 13)^2))))
p

barplot with greek letters and superscripts

like image 22
Dylan Craven Avatar answered Oct 11 '22 03:10

Dylan Craven