I'm trying to create an highcharter bar chart with a shiny input selector in an r markdown document. My problem is that i can't change colors of the bar to make them match the colors i have chosen for my report. It is the first time i use highcharter and probably i'm missing something about the philosophy of highcharter aesthetic
library(tidyverse)
library(highcharter)
df <- tibble(category = c('A1', 'A2', 'A3', 'A4','A5'),
n = c(3415,3701,2898,2409,1886))
mypal <- c("#BC3C29FF", "#0072B5FF", "#E18727FF",
"#20854EFF", "#7876B1FF", "#6F99ADFF","#FFDC91FF","#EE4C97FF")
df %>%
arrange(desc(n)) %>%
hchart( type = 'bar', hcaes(x = category, y = n, color = category))%>%
hc_title(text = 'Most Reported Categories') %>%
hc_xAxis(title = '') %>%
hc_add_theme(hc_theme_elementary()) %>%
hc_colors(mypal)
The code does not seem to care about the last line hc_colors and the following is my output
My goal is to have different colors for every bar (something similar to ggplot2::scale_fill), but i want the colors to be chosen from mypal
I have tried
df %>%
arrange(desc(n)) %>%
hchart( type = 'bar', hcaes(x = category, y = n), color = category)%>%
hc_title(text = 'Most Reported Categories') %>%
hc_xAxis(title = '') %>%
hc_add_theme(hc_theme_elementary()) %>%
hc_colors(mypal)
And
df %>%
arrange(desc(n)) %>%
hchart( type = 'bar', hcaes(x = category, y = n), color = mypal)%>%
hc_title(text = 'Most Reported Categories') %>%
hc_xAxis(title = '') %>%
hc_add_theme(hc_theme_elementary()) %>%
hc_colors(mypal)
Especially the latter gives me this bizarre output.
I have been working on this for hours not reaching any satisfactory result. As I said before the solution is probably obvious and I'm missing something about how highcharter
works.
Thanks for any help.
CodePudding user response:
You could create a column with the colors you want to give each bar. Here is an example using mutate
by calling the column "mypal" with the first five colors of your vector:
library(tidyverse)
library(highcharter)
#> Registered S3 method overwritten by 'quantmod':
#> method from
#> as.zoo.data.frame zoo
df <- tibble(category = c('A1', 'A2', 'A3', 'A4','A5'),
n = c(3415,3701,2898,2409,1886))
mypal <- c("#BC3C29FF", "#0072B5FF", "#E18727FF",
"#20854EFF", "#7876B1FF", "#6F99ADFF","#FFDC91FF","#EE4C97FF")
df %>%
mutate(mypal = mypal[1:5]) %>%
arrange(desc(n)) %>%
hchart( type = 'bar', hcaes(x = category, y = n, color = mypal))%>%
hc_title(text = 'Most Reported Categories') %>%
hc_xAxis(title = '') %>%
hc_add_theme(hc_theme_elementary())
Created on 2022-09-25 with reprex v2.0.2