Home > Blockchain >  ggplot2: scale_fill_manual with symbol and shape
ggplot2: scale_fill_manual with symbol and shape

Time:07-17

How do I assign circle and period shapes in ggplot2? Right now I can do two shapes or two symbols but not both.

data.frame(
    x = rnorm(10),
    y = rnorm(10),
    group = gl(2, 5, labels = c("circle", "period"))
    ) %>% 
    ggplot(aes(x = x, y = y, shape = group))  
    geom_point(size = 4)  
    # scale_shape_manual(values = c("a", "."))   # okay
    # scale_shape_manual(values = c("circle", "square"))   # okay
    scale_shape_manual(values = c("circle", ".")) # error

CodePudding user response:

Based on this comment I don't think you can mix symbols and number references. But (the same comment) shows all possible shapes and their corresponding numbers. The period is 46 and circle is 1.

Using the numbers for the shapes you want:

data.frame(
  x = rnorm(10),
  y = rnorm(10),
  group = gl(2, 5, labels = c("circle", "period"))
) %>% 
  ggplot(aes(x = x, y = y, shape = group))  
  geom_point(size = 4)  
  scale_shape_manual(values = c(1, 46)) 

I like using a named character vector to define the manual shapes for each group.

plotting_shapes <- c("group_1" = 1,
                     "group_2" = 46)

data.frame(
      x = rnorm(10),
      y = rnorm(10),
      group = gl(2, 5, labels = c("group_1", "group_2"))
    ) %>% 
      ggplot(aes(x = x, y = y, shape = group))  
      geom_point(size = 4)  
      scale_shape_manual(values = plotting_shapes)

And so if you really wanted to use "." to refer to shape 46, then you could achieve this through the following:

plotting_shapes <- c("circle" = 1,
                     "." = 46)

data.frame(
  x = rnorm(10),
  y = rnorm(10),
  group = gl(2, 5, labels = c("group_1", "group_2"))
) %>% 
  ggplot(aes(x = x, y = y, shape = group))  
  geom_point(size = 4)  
  scale_shape_manual(values = plotting_shapes[c("circle", ".")] %>%
                       unname()) # unname() is required because 
                                 # the names don't correspond to 
                                 # the group names "group_1" and "group_2"
  • Related