Search code examples
rplotr-highchartercolumn-chart

Change default Series 1 for a changing name


I have a column chart and I want to modify the name that is inside the column. The problem is that I do not want a static name neither the default one (Series 1)

The code is the following:

df <-
  structure(
    list(
      CCAA = c(
        "ANDALUCÍA",
        "CEUTA",
        "COMUNITAT VALENCIANA",
        "CASTILLA-LA MANCHA",
        "EXTREMADURA",
        "CASTILLA Y LEÓN"
      ),
      TOTAL = c(27,
                14, 4, 2, 2, 1),
      COLOR = c(
        "#E30613",
        "#E30614",
        "#E30615",
        "#E30616",
        "#E30617",
        "#E30618"
      ),
      BANDERAS = c(
        "FLAG 1",
        "FLAG 2",
        "FLAG 3",
        "FLAG 4",
        "FLAG 5",
        "FLAG 6"
      )
    ),
    class = c("tbl_df", "tbl", "data.frame"),
    row.names = c(NA,-6L)
  )

And the code of the highcharter plot is:

grafico <- highchart() %>%
    hc_chart(type = 'column') %>%
    hc_tooltip(table=TRUE) %>%
    hc_xAxis(categories = df$BANDERAS) %>%
    hc_colors(color=df$COLOR) %>%
    hc_exporting(enabled = TRUE) %>%
    hc_legend(enabled=FALSE) %>%
    hc_plotOptions(series = list(animation = FALSE)) %>% 
    hc_add_series(df$TOTAL, dataLabels = list(enabled = TRUE, format='<span style="fontfamily: sans-serif">{point.y}</span>'), colorByPoint=TRUE)

How can I do to put at Series 1, the name of the CCAA instead of the default one, and at the x axis the different names of BANDERA?


Solution

  • You can customize the tooltip using hc_tooltip and a custom JS formatter function:

    library(highcharter)
    
    highchart() %>%
      hc_chart(
        type = "column"
      ) %>%
      hc_tooltip(table = TRUE) %>%
      hc_xAxis(categories = df$BANDERAS) %>%
      hc_colors(color = df$COLOR) %>%
      hc_exporting(enabled = TRUE) %>%
      hc_legend(enabled = FALSE) %>%
      hc_plotOptions(
        series = list(
          animation = FALSE
        )
      ) %>%
      hc_add_series(
        data = df[c("TOTAL", "CCAA")] |> dplyr::rename(y = TOTAL),
        dataLabels = list(
          enabled = TRUE,
          format = '<span style="fontfamily: sans-serif">{point.y}</span>'
        ),
        colorByPoint = TRUE
      ) |>
      hc_tooltip(
        formatter = JS(
          "
          function () {
            return '<b>' + this.points[0].point.CCAA + '</b>:' + this.y;
          }
          "
        )
      )
    

    enter image description here