0

here's a data frame as example.

library(tidyverse)
library(ggpattern)

dat <- data.frame(drv = c("4", "4", "4", "4", "4", "f", "f", "f", "f", "r", "r", "r"), 
                  class = c("compact", "midsize", "pickup", "subcompact", "suv", 
                            "compact", "midsize", "minivan", "subcompact", 
                            "2seater", "subcompact", "suv"), 
                  y = c(12L, 3L, 33L, 4L, 51L, 35L, 38L, 11L, 22L, 5L, 9L, 11L)) 

dat

x11();dat %>% ggplot(aes(x = class, y = y ,fill = drv, pattern = drv)) +
  #  geom_col()+   # not necessary
  geom_col_pattern() +
  coord_flip()       +
  theme_minimal()    +
  scale_fill_manual(
    name = "Drive",
    values = c("4" = "#EEF12B",
               "f" = "#D058EC",
               "r" = "#FF27D5"),
    labels = c(expression(italic("4"),
                          italic("f"),
                          italic("f")))
  ) +
  scale_pattern_manual(name = "Drive",
                       values = c("4" = "none",
                                  "f" = "stripe",
                                  "r" = "none")
  )+
  scale_pattern_fill_manual(
    values = c("f"  = "#5284D9")
  )

and here's the plot I got : enter image description here I would like to merge my both legends, in order to have the background colored but only the f class striped. Trough my code I also wanted to custom the color of the stripe but did not succeed.

Any suggestions ?

HMK
  • 47
  • 4

1 Answers1

1

To merge your legends you have to use the same labels for scale_pattern_manual as for scale_fill_manual:

library(ggplot2)
library(ggpattern)

ggplot(dat, aes(x = class, y = y, fill = drv, pattern = drv)) +
  geom_col_pattern() +
  coord_flip() +
  theme_minimal() +
  scale_fill_manual(
    name = "Drive",
    values = c(
      "4" = "#EEF12B",
      "f" = "#D058EC",
      "r" = "#FF27D5"
    ),
    labels = c(expression(
      italic("4"),
      italic("f"),
      italic("f")
    ))
  ) +
  scale_pattern_manual(
    name = "Drive",
    values = c(
      "4" = "none",
      "f" = "stripe",
      "r" = "none"
    ),
    labels = c(expression(
      italic("4"),
      italic("f"),
      italic("f")
    ))
  ) +
  scale_pattern_fill_manual(
    values = c("f" = "#5284D9")
  )

stefan
  • 90,330
  • 6
  • 25
  • 51