2

My code worked early, but the legends for shape and color become separated now.

## loading packages
library(tibble)
library(ggplot)
## an example of data
my_data <- tibble(x = seq(1:10), 
                 y = rnorm(10, mean = 0, sd = 1),
                 z = rep(c("{ }^{2}*H", "{ }^{18}*O"), 5))

An example of a data set can be like this:

my_data
# A tibble: 10 x 3
       x       y z         
   <int>   <dbl> <chr>     
 1     1  0.631  { }^{2}*H 
 2     2  1.43   { }^{18}*O
 3     3 -0.548  { }^{2}*H 
 4     4 -1.42   { }^{18}*O
 5     5  1.72   { }^{2}*H 
 6     6 -0.816  { }^{18}*O
 7     7  0.0297 { }^{2}*H 
 8     8 -0.471  { }^{18}*O
 9     9 -0.565  { }^{2}*H 
10    10  0.448  { }^{18}*O

When I wanted to draw a simple point-line plot, with the following code:

my_colors <- c("#00BFC4", "#F8766D")

ggplot(data = my_data,
       mapping = aes(x = x, y = y, color = z, shape = z)) +
  geom_point() +
  geom_line() +
  scale_color_manual(name = "", 
                     labels = parse_format(),
                     values = my_colors) +
  scale_shape_manual(name = "", 
                     labels = parse_format(),
                     values = c(16:17)) 

The legends are separated, as shown in the following figure: enter image description here

But it was worked smoothly ealier, as shown in the following figure:

enter image description here

2
  • If the name and labels are the same then only one legend should be drawn. It is not happening in this case so I think a bug was recently added related to using either parse_format() or label_parse() in the scale_*_manual() statements
    – Dave2e
    Commented Sep 2, 2020 at 2:45
  • Probably, because it worked earlier for me.
    – Sam
    Commented Sep 2, 2020 at 3:42

1 Answer 1

1

Here is my newest update. You can use as.expression and bquote

ggplot(data = my_data, mapping = aes(x = x, y = y, color = z, shape = z, group = z)) +            
  geom_point() +            
  geom_line() +    
  scale_color_discrete(name = "", labels = c(as.expression(bquote({ }^{2}*"H")), as.expression(bquote({ }^{18}*"O"))))+
  scale_shape_discrete(name = "", labels = c(as.expression(bquote({ }^{2}*"H")), as.expression(bquote({ }^{18}*"O"))))

enter image description here

1
  • when I use something similar to your code, as follows: ggplot(data = my_data, mapping = aes(x = x, y = y, color = z, shape = z)) + geom_point() + geom_line() + scale_color_discrete(name = "", labels = c(expression({ }^{2}*"H"), expression({ }^{18}*"O")))+ scale_shape_discrete(name = "", labels = c(expression({ }^{2}*"H"), expression({ }^{18}*"O"))) It is still not work. I guess it might be related to the expressions.
    – Sam
    Commented Sep 2, 2020 at 3:38

Not the answer you're looking for? Browse other questions tagged or ask your own question.