Saurabh Tiwari
Saurabh Tiwari

Reputation: 5161

How can I access the 'this' field in plotOptions of highcharts

I am trying to achieve two things:

  1. Apply a green or red color based on the data point of a column chart in highcharts. Lets say if column is above 50, border is green else red.

  2. I want to place a icon (if icon not possible, at least a text) inside few chart based on if they have some property.

I am trying to do following:

plotOptions:{
        column:{
            borderColor: this.y > 50 ? 'green' : console.log(this),
            dataLabels: {
                            format: this.prop : 'i': '', //will put 'i' as icon
                            enabled: true,
                            align: 'top',
                            color: '#fff',
                            inside: true
                        }
        },

    },

My bar chart series is :

 series: [{
            name: 'Defect per sprint',
            data: [0, 0, 0, 2, 10, 2, 5, 3]
            }]

If I keep borderColor with series it gets applied to all columns But it seems plotOptions is not supplied the 'this' instance. So the above code doesn't work. How can I achieve the above ??

Upvotes: 2

Views: 331

Answers (2)

lucasnadalutti
lucasnadalutti

Reputation: 5958

1) I'm not aware of a way to do this on chart creation. You can, though, loop over the series array after creating your chart to update each column's border color. Inside your loop, you'd use the update method after checking if the column value is above 50. Sample below:

chart.series[i].update({borderColor: '#00FF00'})

2) I haven't used Highcharts for some time now but the following used to work: instead of format, define a formatter function.

dataLabels: {
  formatter: function () {return this.prop ? 'i' : ''}, //will put 'i' as icon
  ...
}

Upvotes: 1

jlbriggs
jlbriggs

Reputation: 17800

I would do this by preprocessing the data.

You can loop through the data array and check for any value, and apply any level of formatting accordingly.

Example:

var data = [1, 2, 3, 5, 9, 8, 7, 4, 5, 6, 9, 7, 5, 3, 6, 9, 7, 5, 9],
  processedData = [];

$.each(data, function(i, point) {
  processedData.push(
    (
      point < 6 ? {
        "y": point,
        "color": "rgba(204,0,0,0.75)",
        "dataLabels": {
          "enabled": true
        }
      } : point
    )
  )
});

This loops through an array, checks for a value of less than 6 - if found, it applies a different color to the point, and enables the data label, otherwise, it just adds the point as a single value, and the chart config determines its color and other properties.

In the chart config, you specify the details of the dataLabels properties, and set enabled: false, so that they are only used for the points that you've enabled them for.

Fiddle:

Output:

screenshot

Upvotes: 1

Related Questions