Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

setting some colors of ggplot with the same colour and get rid of labels

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading