简体   繁体   中英

ggplot2: how to assign math symbols to legend labels for two different aesthetics?

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() 

情节

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]))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM