0

I have a much larger dataframe but I post here a tow example for reproducibility.

df = data.frame(fc_col = c(rep('apple',3),rep('orange',3),rep('banana',3)),var1 = c(rep(1:3,3)),var2 = c(20,10,5,30,15,2,40,27,8))

If I plot:

> ggplot(data=df, aes(x=var1, y=var2,colour = fc_col))+
+     geom_line()

I get this:

enter image description here

I would like to get something like apple to black and banana orange to a single color say blue. Imagine there are not 3 levels of factor fc_col like in this case but 300. I would also like to get rid of the label banana orange and write a single one say fruits and have it there with the blue color as mentioned.

moth
  • 1,833
  • 12
  • 29

1 Answers1

1

This may helps.

The trick is, keep fc_col that keeps fruits themselves, will be used as group in aes(). And make another variable new_fac for color argument .

library(dplyr)
library(ggplot2)

df %>%
  mutate(new_fac = ifelse(fc_col == "apple", fc_col, "fruits") %>% as.factor()) %>%
  ggplot(aes(var1, var2, colour = new_fac, gruop = fc_col)) +
  geom_line() +
  scale_color_manual(values = c("black", "blue"))

enter image description here

data.table

library(data.table)
df2 <- setDT(df)[,new_fac := ifelse(fc_col == "apple", "apple", "fruits")][]
ggplot(df2, aes(var1, var2, colour = new_fac, gruop = fc_col)) +
  geom_line() +
  scale_color_manual(values = c("black", "blue"))
Park
  • 14,771
  • 6
  • 10
  • 29
  • ok are you modifying the dataframe with `mutate` ? how are the lines being kept if by the time you plot there are only two levels of factor `new_fac` – moth Nov 24 '21 at 07:37
  • 1
    @moth In `aes` part, `color` is from `new_fac` and `group` is from `fc_col`. – Park Nov 24 '21 at 07:38
  • ok cool, I wonder if there is a `data.table` approach to that since the pipe `%>%` is feeding directly to the ggplot command – moth Nov 24 '21 at 07:40
  • 1
    @moth in R base it would be `df$fc_col_new <- ifelse(df$fc_col == "apple", "apple", "fruits")` –  Nov 24 '21 at 07:41
  • oh yes `data.table` here https://rdrr.io/cran/data.table/man/fifelse.html – moth Nov 24 '21 at 07:44
  • 1
    @moth I add `data.table` version code. I'm not sure if that's what you were looking for. – Park Nov 24 '21 at 07:46
  • for the posterity, the key of this answer is the `group` aesthetic, and create a new column for the color aesthetic – moth Nov 24 '21 at 07:47
  • 1
    @Park that's good thanks. maybe if you add two lines about the explicit `group` aesthetic it may help others, I didn't know about it but now I know – moth Nov 24 '21 at 07:48
  • 1
    @moth I add little explanation about it. :D – Park Nov 24 '21 at 07:51