Helga
Helga

Reputation: 101

Subscripts (or other math formula) in ggplot2 legend factor labels

I tried to add subscripts to my ggplot2 geom_point colour legend by using scale_colour_discrete. Similar problems popped up here

p <- ggplot(myData, aes(myFeature1,myFeature2))
p <- p + geom_point(aes(colour = myFeature3)) + facet_grid(n ~ cond)
p <- p + scale_colour_discrete(breaks = levels(myData$myFeature3), labels = c(expression(myFeature3[1]),expression(myFeature3[2]))

However, the following error occurs: Error in FUN(X[[1L]], ...) : cannot coerce type 'symbol' to vector of type 'double'

This error does NOT occur, without in the labels definition expression. It DOES occur whatever is inside the expression.

Any ideas on the subject? Does scale_colour_discrete just not work with expression? Is there another way to get subscripts into those legend factor names?

Thanks a lot!

Upvotes: 3

Views: 5415

Answers (2)

Peter
Peter

Reputation: 7790

Here is an example using the diamonds data set where the labels for the diamond cut are replaced by Cut_1, ..., Cut_5.

ggplot(diamonds, aes(x = carat, y = price)) + 
  geom_point(aes(colour = cut)) + 
  facet_grid(color ~ clarity) + 
  scale_colour_discrete(breaks = levels(diamonds$cut), 
                        labels = c(expression(Cut[1]),
                                   expression(Cut[2]),
                                   expression(Cut[3]),
                                   expression(Cut[4]),
                                   expression(Cut[5])))

If this is not helping you find a solution to your problem can you provide a reproducible example for others to trouble shoot?

Upvotes: 2

Spacedman
Spacedman

Reputation: 94192

Can't replicate this without your data. Trying something similar with the 'diamonds' data as described in help(scale_colour_discrete):

d + scale_colour_discrete(breaks=levels(diamonds$clarity),labels=rep(expression(a^2),8))

works, labelling all levels with a-squared in math notation.

d + scale_colour_discrete(breaks=levels(diamonds$clarity),labels=rep(expression(clarity[1]),8))

works, labelling with clarity subscript 1 in all levels.

Upvotes: 1

Related Questions