R highcharter条形图中的自定义颜色

Custom colors in R highcharter barplot

我正在尝试使用 higcharter 包生成带有图例和自定义颜色的条形图。

首先是数据:

dta <- structure(list(antibiotic = c("Ceftriaxone", "Ampicillin", "Gentamicin", 
                                     "Meropenem", "Cefotaxime", "Cloxacillin", "Metronidazole", "Vancomycin", 
                                     "Ceftazidime", "Penicillin V", "Amoxicillin", "Azithromycin", 
                                     "Cefixime", "Clindamycin", "Doxycycline", "Moxifloxacin"), 
                      category = structure(c(1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L, 1L), 
                                           .Label = c("Watch", "Access", "Reserve", "Unknown"), class = "factor"), 
                      n = c(148L, 92L, 44L, 30L, 13L, 12L, 7L, 3L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L)), 
                 class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -16L))

第一次尝试:

library(highcharter)
cols <- c("#2c3e50", "#f39c12")

dta %>%
  hchart(type = "bar", hcaes(x = "antibiotic", y = "n", group = "category"), color = cols) %>%
  hc_yAxis(title = "", stackLabels = list(enabled = TRUE)) %>% 
  hc_xAxis(title = "") %>%
  hc_tooltip(headerFormat = "",
             pointFormat = "{point.n} patients have taken {point.antibiotic}") %>%
  hc_plotOptions(series = list(stacking = "normal"))

颜色和图例符合预期,但生成的绘图首先按 category 对元素进行排序,而我希望按 n 对元素进行排序

我试过:

dta %>%
  hchart(type = "bar", hcaes(x = "antibiotic", y = "n", color = "category")) %>%
  # hc_colors(c("#2c3e50", "#f39c12")) |> 
  hc_yAxis(title = "", stackLabels = list(enabled = TRUE)) %>% 
  hc_xAxis(title = "") %>%
  hc_tooltip(headerFormat = "",
             pointFormat = "{point.n} patients have taken {point.antibiotic}") %>%
  hc_plotOptions(series = list(stacking = "normal"))

现在排序很完美,但是图例消失了,我也不能自定义颜色。我尝试向数据框添加一列颜色并使用 hc_colors()

让它工作有点痛苦,但我相信这是解决你问题的方法。不幸的是,似乎没有办法直接使用 highcharts 执行此操作,因此您必须事先处理数据。

library(highcharter)
library(tidyverse)
cols <- c("#2c3e50", "#f39c12")
dta %>% 
  ungroup() %>% 
  mutate(antibiotic = factor(antibiotic) %>% fct_reorder(n, .desc = TRUE)) %>% 
  mutate(cat_index = as.numeric(antibiotic)) %>% 
  hchart(
    type = "bar",
    hcaes(x = cat_index,
          y = n,
          group = category,
          name = antibiotic),
          color = cols
  ) %>%
  hc_xAxis(type = "category", labels = list(step = 1)) %>% 
  hc_yAxis(title = "", stackLabels = list(enabled = TRUE)) %>%
  hc_tooltip(headerFormat = "",
             pointFormat = "{point.n} patients have taken {point.antibiotic}") %>%
  hc_plotOptions(series = list(stacking = "normal"))