Search code examples
rhighchartsr-highcharter

How can I show the label next to the bar in r highcharter?


I am trying to create a bar chart where the x-axis labels are located next to the bars. My desired result would be similar to:

https://i.sstatic.net/LuPIV.png (from: HighCharts Place Label on Bar)

However, there are two differences:

  • I am making my chart in R highcharter

  • I don't wan't the labels inside the bars, but next to them. It should look similar to how you would normally add a value next to a bar, see for example:

enter image description here

I have tried offsetting the labels, but since I don't want them to be on a fixed position, but on a position relative to the bars, this did not work.

I have also tried to use annotations, but I'm not fimiliar enough with those to get it to work properly. My original example allows the user to select a specific series. So the location has to be dynamic,but when I use the annotations I can only get them to appear at a fixed point.

Here is a very basic example of what my chart looks like:

library(highcharter)

#create dataframe
data <- data.frame(
  type_1 = c("a", "a", "b", "b", "c", "c"),
  type_2 = c("1", "2", "1", "2", "1", "2"),
  n = c(5,8,10,4,7,9))
data

# create chart
highchart() %>% 
  hc_add_series(data, type = "bar", hcaes(x = type_1, group = type_2, y = n)) %>% 
  hc_plotOptions(series = list(stacking = 'normal')) %>%
  hc_xAxis(categories = unique(data$type_1)

What I would like is for the a / b/ c not to appear in the legend, but to be shown next to the bar.

Thank you for any help you could offer!


Solution

  • You don't need to use annotations. It's easier to use dataLabels. They are placed in place you want by default and you can display in them whatever you want using dataLabels.formatter. Of course, you can disable xAxis labels now.

    This is an example (I defined an array labels and return from it, but you can return values from your type_1 list):

    library(highcharter)
    
    #create dataframe
    data <- data.frame(
      type_1 = c("a", "a", "b", "b", "c", "c"),
      type_2 = c("1", "2", "1", "2", "1", "2"),
      n = c(5,8,10,4,7,9))
    data
    
    # create chart
    highchart() %>% 
      hc_add_series(data, type = "bar", hcaes(x = type_1, group = type_2, y = n), dataLabels = list(
      enabled = TRUE,
      formatter = JS(
        "function() {
          var labels = ['a', 'b', 'c'];
          return labels[this.point.x];
        }"
      ))) %>% 
      hc_xAxis(categories = data$type_1)
    

    Final effect with above code

    API Reference: https://api.highcharts.com/highcharts/series.column.dataLabels

    Pure JS example: https://jsfiddle.net/BlackLabel/nrtax718