You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R语言highcharter绘制自定义颜色条形图排序与图例共存问题

解决方法

提前对antibiotic字段做因子化排序,固定x轴的显示顺序,即可同时满足按n降序排列、保留分组图例、自定义颜色的需求,完整代码如下:

library(highcharter)

# 原始数据
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))

# 核心步骤:将antibiotic按n降序设置为因子,固定x轴顺序
dta$antibiotic <- factor(dta$antibiotic, levels = dta$antibiotic[order(-dta$n)])

# 绘图(沿用第一次的写法即可)
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"))

原问题原因说明

  • 第一次代码用group参数映射category字段,highcharter默认会按分组顺序排列x轴类目,提前固定因子levels后会覆盖默认排序逻辑
  • 第二次代码把category映射到了color而非group,highcharter仅会为group映射的字段生成分组图例,因此出现图例消失的问题

内容的提问来源于stack exchange,提问作者tic-toc-choc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 22:36:03