Home > Software engineering >  Dynamic vector for feeding colours elsewhere
Dynamic vector for feeding colours elsewhere

Time:10-20

I'm trying to provide some specific colours to colour-code a dynamic chart based on the category of variables being plotted. The chart is unfortunately somewhat inflexible; if I give too many colours (or too little) for the number of different categories of data, there will be an error and the chart won't be produced.

What I've done thus far is pass a vector with the 'library of colours' that I want the chart to use to plot:

colours <- c("#FF5733", "#FFF333", "#33A8FF", "#D733FF", "#FF3368", "#33FCFF", "#55FF33")

My thinking is that I need to do the following to find out the number of categories of data in the dynamic dataset each time:

different_cats <- n_distinct(df$`Method Category`)

Then write an explicit for each possible event (if different_cats == X...); but I'm unsure whether that syntax is appropriate, or whether this event he best way to get over the problem.

CodePudding user response:

You can use different_cats to index your list of colours:

colours <- c("#FF5733", "#FFF333", "#33A8FF", "#D733FF", "#FF3368", "#33FCFF", "#55FF33")

different_cats <- 3

colours[1:different_cats]
#> [1] "#FF5733" "#FFF333" "#33A8FF"

Created on 2022-10-19 with reprex v2.0.2

  • Related