Highcharter:图例未与 hchart() 中的 "color" 参数一起出现

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

我使用 highcharter 制作了一个图,其中我的 x 轴是一个离散的产品变量,我的 y 轴是销售单位的总价格,我用数字给条形图上色售出的单位。默认情况下,没有图例。我也在努力自定义调色板(默认使用 viridis)。

示例数据如下:

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

到目前为止我在 highcharter 中所做的事情:

library(highcharter)
library(viridis)

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

我想要的示例(使用 ggplot):

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

理想情况下,我还希望能够选择调色板,例如:

scale_fill_viridis_b(option = "magma")

运行成类似问题。这是我解决问题的最佳尝试:

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)}"))

reprex package (v2.0.1)

于 2022-03-05 创建