Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show plot lines in the legend in Highcharts?

I not only want my legend to contain series' names, I also want it to contain name of my other items like my plotline. Here is my code:

plotLines: [
    {
        color: 'red',
        dashStyle: 'shortdash',
        value: response.AverageTime,
        width: 2,
        label: {
            text: response.PlotLineName, 
            x: +10, 
            y: +30,
            rotation: 360,
            color: 'red'
        }
    }
]

So I want my plotline's name which is "Average Velocity Deviation" looks like in the legend box like below. How can I achieve that?

enter image description here

like image 868
MinhNguyen Avatar asked Sep 18 '15 18:09

MinhNguyen


2 Answers

You can create an empty series which mimics the characteristics of the plot line (color, dash style...). You can then optionally use the legendItemClick event to "link it up" to the plot line.

For example, you predefine these variables for ID and plot line options:

plotLineId = 'myPlotLine'; // To identify for removal

// Plot line options for adding
plotLineOptions = {
    color: '#FF0000',
    id: plotLineId, 
    width: 2,
    value: 5.5,
    dashStyle: 'shortdash'
};

Your axis plotline:

xAxis: {
    plotLines: [ plotLineOptions ]
}

Your mimic series:

series: [
    // ...
    {
        // Series that mimics the plot line
        color: '#FF0000',
        name: 'My plotline',
        dashStyle: 'shortdash',
        marker: {
            enabled: false
        },
        events: {
            // Event for showing/hiding plot line
            legendItemClick: function(e) {
                if(this.visible) {
                    this.chart.xAxis[0].removePlotLine(plotLineId);
                }
                else {
                    this.chart.xAxis[0].addPlotLine(plotLineOptions);
                }
            }
        }
    }
]

See this JSFiddle demonstration of how it works (or this minimal example, without events).

like image 60
Halvor Holsten Strand Avatar answered Nov 01 '22 21:11

Halvor Holsten Strand


Just as an alternative, if you're going to go so far as to make a fake series that mimics all of the aspects of your plot line...

You can just use that series as your plotLine, and skip all of the extra work of tying everything together...

like:

{  
  name: 'Plot Line',
  color: 'red',
  type:'line',
  dashStyle: 'shortdash',
  lineWidth: 2,
  data: [[minXvalue, plotLineValue], {x:maxXvalue, y:plotLineValue, dataLabels: { enabled: true }}]
}

Example:

  • http://jsfiddle.net/jlbriggs/3d3fuhbb/74/
like image 27
jlbriggs Avatar answered Nov 01 '22 21:11

jlbriggs