Reputation: 916
I am trying to produce a legend with math symbols. I tried different options but none works. I don't find a way to assign labels directly to the guide_legend
and ggplot doesn't seem to understand expression
s in factor levels. Also giving label_bquote
to factor levels fails (in any case, the ggplot2 documentation says it works for facets strips).
In the example below I want to change L1, L2 and Linf to L's with subscripts 1, 2, and the infinity symbol, respectively.
a1 = exp(seq(1, 3))
a2 = exp(seq(1, 3) + 0.2)
a3 = exp(seq(1, 3) + 0.4)
df = data.frame(coefficients = c(a1, a2, a3), order = rep(1:3, 3),
norm = factor(rep(1:3, each = 3), labels = expression(L[1], L[2], L[inf])))
ggplot(df, aes(x = order, y = coefficients, colour = norm, shape = norm)) +
geom_line() + geom_point()
Upvotes: 1
Views: 3996
Reputation: 916
I had overlooked that a similar question had already been asked and the answers give the right hint: assign the labels via the scales, as shown below. Note that the both scales must be defined and that both must have the same name and labels, in order to avoid producing two legends.
a1 = exp(seq(1, 3))
a2 = exp(seq(1, 3) + 0.2)
a3 = exp(seq(1, 3) + 0.4)
df = data.frame(coefficients = c(a1, a2, a3), order = rep(1:3, 3),
norm = factor(rep(1:3, each = 3), labels = c("L1", "L2", "Linf")))
ggplot(df, aes(x = order, y = coefficients, colour = norm, shape = norm)) +
geom_line() + geom_point() +
scale_colour_manual(name = "norm", values = c("blue", "red", "green"),
labels = expression(L[1], L[2], L[infinity])) +
scale_shape_discrete(name = "norm",
labels = expression(L[1], L[2], L[infinity]))
Upvotes: 4