1
votes

I have a data frame separated by 3 different factors. I want to represent this data frame with a scatter plot, using different types of scale for each factor.

I want to use shapes 21, 22 and 24, which are shapes with an outline and a colored filling. However, the filling scale does not appear correctly in the legend. Also, I want to unify the legend so that the labels look something like this (in the MWE I represented these labels with numbers from 1 to 18 (labels = 1:18)):

  • A, M, V1
  • A, M, V2
  • A, M, V3
  • ...
  • B, O, V2
  • B, O, V3

I followed the recommendations of this answer, but the resulting plot was not as expected. Does anyone know how I can solve this issue?

library(ggplot2)

Factor1 <- c('A', 'B')
Factor2 <- c('M', 'N', 'O')
Factor3 <- c('V1', 'V2', 'V3')

DF <- expand.grid(Factor1 = Factor1,
                  Factor2 = Factor2,
                  Factor3 = Factor3)

DF$Result <- runif(n =18,
                   min = 0,
                   max = 100)

DF <- DF[order(DF[, "Result"]), ]
DF$Order <- 1:18

ggplot(data = DF,
       aes(x = Order,
           y = Result,
           fill = Factor1,
           shape = Factor2,
           size = Factor3)) +
  geom_point() +
  scale_fill_manual(name = "Legend",
                    values = c('blue', 'red'),
                    labels = 1:18) +
  scale_shape_manual(name = "Legend",
                     values = c(21,22,24),
                     labels = 1:18) +
  scale_size_manual(name = "Legend",
                    values = c(2,4,6),
                    labels = 1:18)

enter image description here

1

1 Answers

1
votes

Following your link will give proper result, but it needs pretty amount of effort....I made an example for Factor1 and Factor2.

DF %>%
  rowwise %>%
  mutate(Fac = paste0(c(Factor1, Factor2), collapse = "-") %>% as.factor) %>%
  ggplot(       aes(x = Order,
           y = Result,
           fill = Fac,
           shape = Fac,
           size = Factor3)) +
  geom_point() +
  scale_fill_manual(name = "Legend",
                    values = c('blue', 'red', 'blue', 'red', 'blue', 'red'),
                    labels = c("A-M", "B-M", "A-N", "B-N", "A-O", "B-O")) +
  scale_shape_manual(name = "Legend",
                     values = c(21,21,22,22,24,24),
                     labels = c("A-M", "B-M", "A-N", "B-N", "A-O", "B-O")) +
  scale_size_manual(name = "Legend",
                    values = c(2,4,6),
                    labels = 1:18)

enter image description here

To combine with Factor3, you may start with

DF %>%
  rowwise %>%
  mutate(Fac = paste0(c(Factor1, Factor2, Factor3), collapse = "-") %>% as.factor) %>%
  ggplot(       aes(x = Order,
           y = Result,
           fill = Fac,
           shape = Fac,
           size = Fac))