James
James

Reputation: 526

Highcharter: Legend not appearing with the "color" argument in hchart()

I've produced a plot using highcharter, where my x-axis is a discrete product variable, my y-axis is the total price of the units sold, and I coloured the bars with the number of units sold. By default, there's no legend. I'm also struggling to customize the colour palette (uses viridis as default).

Here's sample data:

library(tidyverse)

sample_df <- tibble(product = c("Product A", "Product B", "Product C","Product D"),
       total_sales = c(15000,12000,9000,18000),
       units_sold = c(62,24,35,24)
)



# A tibble: 4 x 3
  product   total_sales units_sold
  <chr>           <dbl>      <dbl>
1 Product A       15000         62
2 Product B       12000         24
3 Product C        9000         35
4 Product D       18000         24

What I've done so far in highcharter:

library(highcharter)
library(viridis)

sample_df %>%
  hchart('column', hcaes(x = product, y = total_sales, color = units_sold))

enter image description here

An example of what I'd like to have (using ggplot):

sample_df %>%
  ggplot(aes(x = product, y = total_sales, fill = units_sold)) +
  geom_bar(stat = "identity") +
  scale_fill_viridis_b()

enter image description here

Ideally, I'd also like to be able to choose the colour palette, such as:

scale_fill_viridis_b(option = "magma")

enter image description here

Upvotes: 1

Views: 253

Answers (1)

Kene David Nwosu
Kene David Nwosu

Reputation: 898

Ran into similar problems. Here is my best attempt at solving:

library(tidyverse)
library(highcharter)

custom_colors <- c("#1B102D", "#BC4C6E", "#FCF0BB")

sample_df <-
  tibble(
    product = c("Product A", "Product B", "Product C", "Product D"),
    total_sales = c(15000, 12000, 9000, 18000),
    units_sold = c(62, 24, 35, 24)
  ) %>%
  ## manually add colors with colorize function
  mutate(colors = colorize(units_sold, custom_colors)) %>% 
  ## custom tooltip
  mutate(my_tooltip = paste0("<b>Product:</b> ", product, "<br>",
                           "<b>Total sales:</b> ", total_sales, "<br>",
                           "<b>Units sold:</b> ", units_sold))


sample_df %>%
  hchart('column', hcaes(x = product, 
                         y = total_sales, 
                         color = colors)) %>% 
  hc_colorAxis(min=min(sample_df$units_sold),
               max=max(sample_df$units_sold),
               stops= color_stops(colors = custom_colors), 
               marker = NULL ## need to turn off the marker because it does not work correctly for this hacky plot
               ) %>% 
  hc_tooltip(formatter = JS("function(){return(this.point.my_tooltip)}"))

enter image description here

Created on 2022-03-05 by the reprex package (v2.0.1)

Upvotes: 1

Related Questions