1

How can I assign colors to a categorical variable in R highcharter with a stable mapping? I want to use consistent colors across a huge set of figures that have different subsets of this variable. Therefore, I want to define the color mapping globally for all figures.

There is a very similar question using ggplot2. I tried to use the solutions in my case, but so far without success.

This is a minimal example of my data:

faculty cost
physics 8000
life sciences 1050
chemistry 1000

Here is my code so far:

library(tidyverse)
library(highcharter)

ColorPalette <- c("green","blue","red")
names(ColorPalette) <- levels(publications$faculty)

hchart(
  publications,
  "column",
  hcaes(x = faculty, y = cost),
  colorByPoint = TRUE
  ) %>%
  hc_colors(ColorPalette)

Using the defined colors works fine, but when I create figures with a subset of the data only containing some values of the categorical variable, color assignment gets mixed up and is not stable:

1 Answers1

0

An option is assigning the colors (In CSS style using this site: https://www.rapidtables.com/web/color/RGB_Color.html) to the different faculty values using the following code:

library(tidyverse)
library(highcharter)

publications <- data.frame(faculty = c("physics", "life sciences", "chemistry"),
                           cost = c(8000, 1050, 1000))

publications <- mutate(publications, color = ifelse(faculty == "physics", "#00FF00", 
                                             ifelse(faculty == "life sciences", "#0000FF", "#FF0000")))

You don't need to use hc_colors, because you can assign the colors in the hcaes using this code:

hchart(
  publications,
  "column",
  hcaes(x = faculty, y = cost, color = color),
  colorByPoint = TRUE
) 

Output:

enter image description here

Quinten
  • 35,235
  • 5
  • 20
  • 53
  • To add the color assignment in a separate column in the dataframe solves my question. Is there a way to map colours for various dataframes all containing faculty as a variable, or do I have to assign the colours in each dataframe via `mutate`? –  May 01 '22 at 16:52
  • @taze4, Great to hear that solved your question. If the colors are faculty dependent you need to assign them via `mutate`. – Quinten May 01 '22 at 17:06