向ChartJS数据集添加其他属性

Adding additional properties to a Chart JS dataset

本文关键字:其他 属性 添加 数据集 ChartJS      更新时间:2023-09-26

我正在尝试向ChartJS数据集添加额外的属性(对于饼图/圆环图)。我在后端有一段Ruby,它将以下JSON打印到视图中:

[
{"segment": "undetermined",
"label": "Undetermined",
"value": 420193," 
color": "#DECF3F",
"highlight": "#e2d455"
},
{"segment":"peer_review",
"label":"Peer Review",
"value":415212,
"color":"#60BD68",
"highlight":"#72c479"
}
]

"segment"属性是一个额外的属性(库中没有提供),我想让JS在前端使用它。然而,当我将这个JSON封装在canvas标签中时,我无法通过JS访问它。

下面的第二行输出上面的JSON:

<canvas id="review-type" height="235" data-facet="review_status_s">
  <%= @by_review_type %> 
</canvas>

我正在尝试使用getSegmentsAtEvent() API调用(名称碰撞意外)来访问"segment"属性:

   $("#review-type").click(
    function(evt) {
      var activePoints = reviewChart.getSegmentsAtEvent(evt);
      /* extract other properties, then build an URL from them: */
      var url = "/" +locale+ "/catalog?f[" +facet_frag+ "][]=" +segment+ "&q=*:*";
      window.location = url;
    }
  );

然而,当我在JS控制台中检查activePoints时,"segment"不在属性列表中。

我该怎么办?

getSegmentsAtEvent(以及其他图表类型的等价物)返回图表元素(扇区、点、条形图等)。您必须使用任何图表元素属性和数据对象来计算索引,然后使用它来获得所需的其他属性。

例如,如果pieData是您的数据对象

$("#review-type").click(
    function (evt) {
        var activePoints = reviewChart.getSegmentsAtEvent(evt);
        if (activePoints.length)
        alert(pieData.filter(function (e) { return e.label === activePoints[0].label; })[0].segment);
            ...

您也可以在从对象传输到元素的属性上设置其他属性(例如label),但这有点麻烦。


Fiddle-http://jsfiddle.net/nm9ay728/