From 6830c78d552926a6a81b2e1ad3c11bbc75c4c441 Mon Sep 17 00:00:00 2001 From: dchakro <35454738+dchakro@users.noreply.github.com> Date: Thu, 27 Jul 2023 11:21:44 -0700 Subject: [PATCH] function to generate palette for categorical data --- returnPalette.R | 63 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 returnPalette.R diff --git a/returnPalette.R b/returnPalette.R new file mode 100644 index 0000000..e2cafd2 --- /dev/null +++ b/returnPalette.R @@ -0,0 +1,63 @@ +returnPalette <- function(ColorVariable = NULL) { +# #<----------------------------> +# # You must include this section when: +# # Distributing, Using and/or Modifying this code. +# # Please read and abide by the terms of the included LICENSE. +# # Copyright 2023, Deepankar Chakroborty, All rights reserved. +# # +# # Author : Deepankar Chakroborty (https://github.com/dchakro) +# # Website: https://www.dchakro.com +# # Report issues: https://github.com/dchakro/shared_Rscripts/issues +# # License: https://github.com/dchakro/shared_Rscripts/blob/master/LICENSE +# #<----------------------------> + + +# # PURPOSE: +# # Generates an appropriate palette for categorical data based on its length + + + if (class(ColorVariable) == "character") { + colorsNeeded <- length(unique(ColorVariable)) + if (colorsNeeded < 1) { + myPalette <- c("#DD0000") + warning("Nothing to return color for.") + } + if (colorsNeeded > 1 & colorsNeeded < 10) { + myPalette <- palette.colors(n = colorsNeeded, + palette = "Classic Tableau") + } else if (colorsNeeded > 10 & colorsNeeded < 18) { + set.seed(2023) + myPalette <- sample( + palette.colors(n = 10, + palette = "Classic Tableau"), + palette.colors(n = colorsNeeded - 10, + palette = "Set2") + ) + } else if (colorsNeeded > 18) { + myPalette <- sample(hcl.colors(n = colorsNeeded, + palette = "Spectral")) + } + } + if (class(ColorVariable) == "factor") { + colorsNeeded <- length(levels(ColorVariable)) + if (colorsNeeded < 1) { + myPalette <- c("#DD0000") + warning("Nothing to return color for.") + } + if (colorsNeeded > 1 & colorsNeeded < 10) { + myPalette <- palette.colors(n = colorsNeeded, + palette = "Classic Tableau") + } else if (colorsNeeded > 10 & colorsNeeded < 18) { + set.seed(2023) + myPalette <- sample( + palette.colors(n = 10, + palette = "Classic Tableau"), + palette.colors(n = colorsNeeded - 10, + palette = "Set2") + ) + } else if (colorsNeeded > 18) { + myPalette <- sample(hcl.colors(n = colorsNeeded, + palette = "Spectral")) + } + } +} \ No newline at end of file