0

If i plot this data here:

data <- data.frame(Xdata = rnorm(6),                       
               Ydata = rnorm(6),
               Group1 = c("ld-01", "ld-02", "ld-03",
                          "ld-04", "ld-05", "ld-06"),
               
               Group2 = c("ld", "ld", "l",
                          "ld4", "l", "ld6"))
ggplot(data, aes(Xdata, Ydata, color = 
Group2, shape = Group1)) +  
geom_point(size = 7)

I want to replace the upper legend by the one "this on"

1 Answer 1

2

One option would be to map Group1 on the color aes too and use scale_color_manual to assign your desired colors like so:

set.seed(123)

data <- data.frame(
  Xdata = rnorm(6),
  Ydata = rnorm(6),
  Group1 = c(
    "ld-01", "ld-02", "ld-03",
    "ld-04", "ld-05", "ld-06"
  ),
  Group2 = c(
    "ld", "ld", "l",
    "ld4", "l", "ld6"
  )
)

library(ggplot2)

colors <- scales::hue_pal()(4)
pal_color <- colors[c(2, 2, 1, 3, 1, 4)]

ggplot(data, aes(Xdata, Ydata,
  color =
    Group1, shape = Group1
)) +
  geom_point(size = 7) +
  scale_color_manual(values = pal_color)

EDIT if you want to keep both legends and only color the shape legend one way to go is to use the override.aes argument of guide_legend which allows to set the colors like so:

library(ggplot2)

#colors <- scales::hue_pal()(4)
colors <- c("black", "blue", "red", "green")
pal_color <- colors[c(2, 2, 1, 3, 1, 4)]

ggplot(data, aes(Xdata, Ydata,
                 color = Group2, shape = Group1
)) +
  geom_point(size = 7) +
  scale_color_manual(values = colors) +
  guides(shape = guide_legend(override.aes = list(color = pal_color)))

enter image description here

2
  • Aw. Sorry. Have overlooked that. See my edit on how to achieve that.
    – stefan
    Commented Jan 9, 2023 at 18:42
  • (: Should be fixed now. Add a scale_color_manual as in my first approach. But use values = colors. Now you should be able to assign your own colors.
    – stefan
    Commented Jan 9, 2023 at 19:33

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