1

I want to make a diagram where in some legend titles I want to introduce some Latex syntax, but the output does not produce the expected result.

As MWE, here is the code I use:

library(ggplot2)
library(latex2exp)

  ggplot(data, aes(x = Debt, y = Gini_tra, colour = Gamma_param)) +
  geom_line()+
  scale_color_discrete(breaks = levels(df_tra$Gamma_param), 
                       labels  = c("Redistribution", "Egalitarian Tax", TeX("$\\gamma = 0.76$"), TeX("$\\gamma = 0.9$"), "Flat Tax"))

From this code I was expecting to see γ=0.76 and γ=0.9, but instead I only see 0.76 and 0.9.

What I am doing wrong here ?

msh855
  • 1,493
  • 1
  • 15
  • 36

2 Answers2

2

I think that this is the solution that you are looking for :

library(ggplot2)
library(latex2exp)


df <- data.frame(value = rnorm(100, mean = 3),
                 group = as.factor(sample(c(1, 2),
                                          size = 100, replace = T)))


ggplot(df , aes(x = value, y = value, colour = group)) +
  geom_point() + 
  scale_color_hue(labels = unname(TeX(c("$\\gamma = 0.76$", "$\\gamma = 0.96$"))))

My insipiration is the second answer of this post :

How to add Latex code in ggplot2 legend labels?

Rémi Coulaud
  • 1,684
  • 1
  • 8
  • 19
1

We can also use expression from Base R:

library(ggplot2)

ggplot(mtcars, aes(x = hp, y = disp, colour = as.factor(carb))) +
  geom_line()+
  scale_color_discrete(breaks = levels(as.factor(mtcars$carb)), 
                       labels  = c("Redistribution", 
                                   "Egalitarian Tax", 
                                   expression(gamma~"= 0.76"), 
                                   expression(gamma~"= 0.9"), 
                                   "Flat Tax",
                                   "some label1")) +
  theme(legend.text.align = 0)

Output:

enter image description here

acylam
  • 18,231
  • 5
  • 36
  • 45
  • That's also good. But, I have a related question. What if I want legend text be left aligned as opposed to right aligned as they appear to be here ? – msh855 May 24 '19 at 16:03
  • @msh855 Simple, just add `theme(legend.text.align = 0)` – acylam May 24 '19 at 16:56