Home > Enterprise >  Problem displaying correct data in legend
Problem displaying correct data in legend

Time:10-03

The first script below enables me to associate each unique value of cyl to a dot color in the legend. I now want to have cyl = 4 and cyl = 6 to have the same color (blue). My second script tries to display in the legend blue dot for 4, blue dot for 6 and green dot for 8. But this doesn't workout correctely. Would any one have an idea what I should modify in my script to achieve this? Many thanks !

### This works, I get the 3 colors in the legend : 
mtcars$color <- with(mtcars, dplyr::case_when(cyl == 4 ~ "blue", cyl == 6 ~ "red", cyl == 8 ~ "green"))
mtcars$color <- factor(mtcars$color, levels = c("blue","red","green"))

G_mtcars<-mtcars %>%
  ggplot(aes(x=hp, y=mpg,color=color))  
  geom_point()  
  scale_color_identity(
    guide = "legend",
    labels = setNames(unique(mtcars$cyl), unique(mtcars$color)))
plot(G_mtcars)

### When wanting to get 4 and 6 as blue with blue dots and 8 with green dot I get blue dot with 4
### and green dot with 4. The green dot doesn't match with the correct Cyl (8) and I don't get my
### 3 legend lines : dot blue 4, dot blue 6, dot green 8

mtcars$color <- with(mtcars, dplyr::case_when(cyl == 4 ~ "blue", cyl == 6 ~ "blue", cyl == 8 ~ "green"))
mtcars$color <- factor(mtcars$color, levels = c("blue","green"))
[Th][1]
G_mtcars<-mtcars %>%
  ggplot(aes(x=hp, y=mpg,color=color))  
  geom_point()  
  scale_color_identity(
    guide = "legend",
    labels = setNames(unique(mtcars$cyl), unique(mtcars$color)))
plot(G_mtcars)

CodePudding user response:

You could use scale_color_manuel with values and labels like this:

library(ggplot2)
library(dplyr)
mtcars$color <- with(mtcars, dplyr::case_when(cyl == 4 ~ "blue", cyl == 6 ~ "blue2", cyl == 8 ~ "green"))
G_mtcars<-mtcars %>%
  ggplot(aes(x=hp, y=mpg,color=color))  
  geom_point()  
  scale_color_manual(values = c('blue' = 'blue', 'blue2' = 'blue', 'green' = 'green'),
                     labels = c('4', '6', '8'))
plot(G_mtcars)

Created on 2022-10-01 with enter image description here

  • Related