使用 highcharter 更改分组颜色

Change grouping color with highcharter

我有一个包含不同类别的条形图,我为每个类别自定义了条形颜色,但我不知道如何更改下方图点的颜色

我的数据:

library(highcharter)
library(dplyr)

x = structure(list(stat = c("abandonne_pro", "admissible", "admissible", 
                            "admissible", "non_recu", "refuse", "refuse", "en_cours", 
                            "non_recu"), 
                   annee_recep = structure(c(17532, 17532, 17897, 18262, 17897, 17532, 17897, 17897, 17532), class = "Date"), 
                   nb_stat = c(4L, 57L, 112L, 1L, 2L, 5L, 5L, 1L, 1L)), 
              row.names = c(NA, -9L), 
              class = "data.frame",
              .Names = c("stat", "annee_recep", "nb_stat"))

添加颜色变量:

x = x %>%
  mutate(
    color = case_when(
      stat == 'abandonne_pro' ~ '#87CEEB',
      stat == 'admissible' ~ '#7CFC00',
      stat == 'non_recu' ~ '#FF7F50',
      stat == 'refuse' ~ '#FF0000',
      stat == 'en_cours' ~ '#FFFF00',
      TRUE ~ '#C0C0C0'
    ),
    date = format(annee_recep, format="%Y")
  )

图形:

hchart(
  x,
  "column", 
  hcaes(x = annee_recep, y = nb_stat, group = stat, color = color)
) %>% 
  hc_plotOptions(column = list(stacking = "normal"), type = "datetime") %>% 
  hc_xAxis(
    title = list(text = 'Date'),
    type = 'datetime'
  ) %>% 
  hc_yAxis(
    title = list(text = "Nombre de chantier")
  ) %>% 
  hc_add_theme(hc_theme_gridlight())

输出:

感谢您的帮助!

一个简单的解决方案是使用 hc_colors() 手动设置颜色,而不是映射到颜色美学上。试试这个:

library(highcharter)
library(dplyr)
library(tibble)

x <- structure(list(
  stat = c(
    "abandonne_pro", "admissible", "admissible",
    "admissible", "non_recu", "refuse", "refuse", "en_cours",
    "non_recu"
  ),
  annee_recep = structure(c(17532, 17532, 17897, 18262, 17897, 17532, 17897, 17897, 17532), class = "Date"),
  nb_stat = c(4L, 57L, 112L, 1L, 2L, 5L, 5L, 1L, 1L)
),
row.names = c(NA, -9L),
class = "data.frame",
.Names = c("stat", "annee_recep", "nb_stat")
)

x <- x %>%
  mutate(
    color = case_when(
      stat == 'abandonne_pro' ~ '#87CEEB',
      stat == 'admissible' ~ '#7CFC00',
      stat == 'non_recu' ~ '#FF7F50',
      stat == 'refuse' ~ '#FF0000',
      stat == 'en_cours' ~ '#FFFF00',
      TRUE ~ '#C0C0C0'
    ),
    date = format(annee_recep, format="%Y")
  )

# Filter dataset
x <- filter(x, stat != 'en_cours')
# Named color vector
color_vec <- count(x, stat, color) %>% 
  select(stat, color) %>% 
  deframe() %>% 
  unname()

hchart(
  x,
  "column", 
  hcaes(x = annee_recep, y = nb_stat, group = stat)
) %>% 
  hc_plotOptions(column = list(stacking = "normal"), type = "datetime") %>% 
  hc_xAxis(
    title = list(text = 'Date'),
    type = 'datetime'
  ) %>% 
  hc_yAxis(
    title = list(text = "Nombre de chantier")
  ) %>% 
  hc_add_theme(hc_theme_gridlight()) %>% 
  hc_colors(colors = color_vec)

reprex package (v0.3.0)

于 2020-03-19 创建