rr-highcharterpolar-plot

How to create a polar stacked plot with Highcharter in R


With the following dataframe:

df <- structure(list(row_labels = c("La ubicación actual de los contenedores de la ciudad", 
"La falta de limpieza de los solares", "La velocidad a la que circulan los vehículos en la ciudad"
), `Nada problemático` = c(45.1242829827916, 17.3996175908222, 
26.5774378585086), Poco = c(24.8565965583174, 21.7973231357553, 
33.4608030592734), Bastante = c(19.3116634799235, 30.7839388145315, 
23.7093690248566), `Muy problemático` = c(9.75143403441682, 
26.0038240917782, 14.34034416826), `NS/NC` = c(0.956022944550669, 
4.01529636711281, 1.91204588910134)), row.names = c("#Total", 
"#Total1", "#Total2"), class = c("etable", "data.frame"))

I want to create a plot like: enter image description here

But I am not sure that the df is well structured because the code that I am using does not work:

highchart() %>%
  hc_chart(type = 'bar', polar = TRUE) %>%
  hc_xAxis(categories = df$row_labels) %>%
  hc_add_series(df, name = 'Fruits', dataLabels = list(enabled = TRUE)) %>%
  hc_credits(enabled = TRUE) %>%
  hc_exporting(enabled = TRUE) %>%
  hc_pane(endAngle = 270) %>%
  hc_plotOptions(series = list(animation = FALSE))

Solution

  • One option to achieve your desired result would be to add the columns of your data one by one using hc_add_series where for convenience I use Reduce to loop over the columns. Additionally set stacking = "normal" via the plot options to get a stacked radial bar chart.

    library(highcharter)
    #> Registered S3 method overwritten by 'quantmod':
    #>   method            from
    #>   as.zoo.data.frame zoo
    
    highchart() |>
      hc_chart(
        type = "bar",
        polar = TRUE
      ) %>%
      hc_plotOptions(bar = list(
        stacking = "normal"
      )) |>
      hc_xAxis(categories = rev(df$row_labels)) |>
      hc_yAxis(reversedStacks = FALSE) |>
      Reduce(
        \(hc, x) {
          hc_add_series(
            hc,
            rev(df[[x]]),
            name = x,
            dataLabels = list(enabled = TRUE, format = "{point.y:,.1f} %")
          )
        },
        x = names(df)[-1],
        init = _
      ) |>
      hc_credits(
        enabled = TRUE,
        text = "InvestigaOnline.com",
        href = "https://www.investigaonline.com"
      ) %>%
      hc_exporting(enabled = TRUE) |>
      hc_pane(endAngle = 270) |>
      hc_plotOptions(series = list(animation = FALSE))