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

Name and use own colors or color palette for ggplot graphs

I have some colors that I would like to give a name to be able to use them in ggplot graphs without having to write the hex codes by hand each time I write the code for a graph.

For example I have the following hex colors #EBD0FC, #F0FFF0, #BEBEBE that I would like to name "mypink", "mymint", "mygrey".

mycolors <- 
  data.frame(name = c("mypink", "mymint", "mygrey"),
         hex = c("#EBD0FC", "#F0FFF0", "#BEBEBE"))

And I would like to use the colors in a ggplot graph like that:

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

scale_fill_manual(values = c("mypink", "mymint", "mygrey"))

instead of

scale_fill_manual(values = c("#EBD0FC", "#F0FFF0", "#BEBEBE"))

As a follow up question: is there a way to "save" my color palette somewhere (online? and maybe only for me to access?) so that I do not have to specify it at the beginning of each session?

>Solution :

Write a function to translate your names into the hex you defined. for example.

mycolors <- 
  data.frame(name = c("mypink", "mymint", "mygrey"),
             hex = c("#EBD0FC", "#F0FFF0", "#BEBEBE"))

myc <- function(x){
  mycolors$hex[which(x %in% mycolors$name)]
}

waldo::compare(scale_fill_manual(values = c("#EBD0FC", "#F0FFF0", "#BEBEBE")),
          scale_fill_manual(values = myc(c("mypink", "mymint", "mygrey"))))
# ✔ No differences
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