0

I am struggling to get expression to communicate something like 10<=VarName<120. Why does the following code fail?

starwars %>% 
  filter(between(birth_year, 10, 120)) %>% 
  ggplot(aes(x=mass, y=height)) +
  geom_point() +
  labs(title=expression(10<="Birth Year"120))

Notice that this alone works (without the 120 on the end):

starwars %>% 
  filter(between(birth_year, 10, 120)) %>% 
  ggplot(aes(x=mass, y=height)) +
  geom_point() +
  labs(title=expression(10<="Birth Year"))

2 Answers2

0

A possible solution is:

starwars %>% 
  filter(between(birth_year, 10, 120)) %>% 
  ggplot(aes(x=mass, y=height)) +
  geom_point() +
  labs(title=expression(paste(10<="Birth Year<",120, sep = "")))

Another solution (more complex, but better)

starwars %>% 
  filter(between(birth_year, 10, 120)) %>% 
  ggplot(aes(x=mass, y=height)) +
  geom_point() +
  labs(title = parse(text = paste0('"10" <= ', ' ~ "Brith Year" <= ', '~ 120')))
Leonardo
  • 2,439
  • 33
  • 17
  • 31
  • Thanks Leonardo. I did notice, however, that for this solution the "<" sign that is included in the quotes is substantially smaller than the <= next to the 10. Do you know if there is a way to make it look uniform? – Benny Goldman Feb 02 '21 at 16:24
  • I changed my answer. Now it should work in any case – Leonardo Feb 02 '21 at 16:35
  • Thanks Leonardo this is great. I picked this Starwars thing as a simple example. In practice I am making a plot that shows counts in different bins of wage rates (one line for 8<=wage<9, another for 9<=wage<10, ...) and so I am using this to label the lines in the legend. Do you know if there is a way to automate or simplify the amount of text in there as it is going to be a lot to write that 5 or 6 times for each plot. No worries if not. – Benny Goldman Feb 02 '21 at 16:38
  • Without seeing the data it is difficult to give you an answer. But keep in mind that you can pass variables to the expression, so you can at least automate a little bit. If the answer was useful to you, if you want accept it – Leonardo Feb 02 '21 at 16:40
0

In a comment it was added that the numbers are changed frequently so have revised to use bquote:

lo <- 10
hi <- 120
ggplot() + labs(title = bquote(.(lo) <= Birth ~ Year < .(hi)))

screenshot

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341