基于单独的数据系列将字符串添加到highcharts工具提示

时间:2017-11-15 19:23:53

标签: javascript highcharts

我正在尝试使用来自django数据库后端的数据在highcharts中创建条形图

条形图绘制正常但是,我需要在工具提示中悬停时显示除“y值”之外的“contact_note”字符串

来自数据库的数据以以下json格式提供

{
  "chart_data": {
    "dates": [
      "12/12/16",
      "01/28/17",
      "02/10/17",
    ],
    "values": [
      9.0,
      47.0,
      13.0,
    ],
    "contact_notes": [
      "aa",
      "bb",
      "cc"
    ]
  }
}

日期代表x轴,'值'是y轴,我希望工具提示包含' contact_note'的内容。字段

这是我的高级代码:

<script>

$(document).ready(function() {

     var options = {
        chart: {
            renderTo: 'chart_panel',
            type: 'column',
        },
        legend: {enabled: false},
        title: {text: 'Days Between Meetings'},
        tooltip: {
        formatter: function () {
            return "<span style='color:" + this.point.color + "'>\u25CF</span> " + this.series.name + " : <b>" + this.point.y + "</b> " +  contact_notes[this.point.index] + "<br/>";
        }},
        xAxis: {title: {text: null}, labels: {rotation: -45}},
        yAxis: {title: {text: null},
        plotLines: [{
                value: 20,
                color: 'orange',
                dashStyle: 'shortdash',
                width: 1.5}]
        },
        plotOptions: {column: {dataLabels: {enabled: true}}},
        series: [{}],
    };


    var chartDataUrl = "{% url 'chart_data' pk %}"

    $.getJSON(chartDataUrl,
        function(data) {
            options.xAxis.categories = data['chart_data']['dates'];
            options.series[0].name = 'Days between contacts';
            options.series[0].data = data['chart_data']['values'];

            var contact_notes = data['chart_data']['contact_notes'];

            var chart = new Highcharts.Chart(options);
    });

} );

</script>

我有简单的方法将联系人备注附加到系列工具提示吗?

非常感谢

1 个答案:

答案 0 :(得分:0)

当然,从后端保存数据(我只是将其保留在返回的数据对象中)并使用tooltip formatter函数。 point已传递到formatter,并且有index可用于索引数组。

http://jsfiddle.net/yjL551vp/

  tooltip: {
        formatter: function () {
            return "<span style='color:" + this.point.color + "'>\u25CF</span> " + this.series.name + " : <b>" + this.point.y + "</b> " +  data.chart_data.contact_notes[this.point.index] + "<br/>";
        }
    },

编辑: 您当前的问题是contact_notes是在getJSON函数中定义的,因此它超出了formatter函数的范围。在getJSON函数之外定义var

   var chartDataUrl = "{% url 'chart_data' pk %}"
   var contact_notes = [];
    $.getJSON(chartDataUrl,
        function(data) {
            options.xAxis.categories = data['chart_data']['dates'];
            options.series[0].name = 'Days between contacts';
            options.series[0].data = data['chart_data']['values'];

            contact_notes = data['chart_data']['contact_notes'];

            var chart = new Highcharts.Chart(options);
    });