Javascript 如何在 ChartJS 中创建自定义图例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44649247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create custom legend in ChartJS
提问by Denis Lapadatovic
I need to create custom legend for my donut chart using ChartJS library. I have created donut with default legend provided by ChartJS but I need some modification.
我需要使用 ChartJS 库为我的甜甜圈图创建自定义图例。我已经用 ChartJS 提供的默认图例创建了甜甜圈,但我需要一些修改。
I would like to have value above the car name. Also I don't like sticky legend I want to have it separate from donut so I can change the style for fonts, boxes (next to the text "Audi" for example)
我想拥有高于汽车名称的价值。此外,我不喜欢粘性图例,我想将它与甜甜圈分开,这样我就可以更改字体、框的样式(例如,文本“奥迪”旁边)
I know there is some Legend generatorbut I'm not sure how to use it with VueJS - because I'm using VueJS as a framework
我知道有一些Legend 生成器,但我不确定如何将它与 VueJS 一起使用 - 因为我使用 VueJS 作为框架
This is how my legend looks like now - http://imgur.com/a/NPUoi
这就是我的传奇现在的样子 - http://imgur.com/a/NPUoi
My code:
我的代码:
From Vue component where I import a donut component:
从我导入甜甜圈组件的 Vue 组件:
<div class="col-md-6">
<div class="chart-box">
<p class="chart-title">Cars</p>
<donut-message id="chart-parent"></donut-message>
</div>
</div>
Javascript:
Javascript:
import { Doughnut } from 'vue-chartjs'
export default Doughnut.extend({
ready () {
Chart.defaults.global.tooltips.enabled = false;
Chart.defaults.global.legend.display = false;
this.render({
labels: ['Audi','BMW','Ford','Opel'],
datasets: [
{
label: 'Cars',
backgroundColor: ['#35d89b','#4676ea','#fba545','#e6ebfd'],
data: [40, 30, 20, 10]
}
]
},
{
responsive: true,
cutoutPercentage: 75,
legend: {
display: true,
position: "right",
fullWidth: true,
labels: {
boxWidth: 10,
fontSize: 14
}
},
animation: {
animateScale: true
}
})
}
});
回答by Italo Borges
I'm having the same problem trying to understand the documentation and this link might clarify the process of customize the legends:
我在尝试理解文档时遇到了同样的问题,此链接可能会阐明自定义图例的过程:
https://codepen.io/michiel-nuovo/pen/RRaRRv
https://codepen.io/michiel-nuovo/pen/RRaRRv
The trick is to track a callback to build your own HTML structure and return this new structure to ChartJS.
诀窍是跟踪回调以构建您自己的 HTML 结构并将这个新结构返回给 ChartJS。
Inside the options object:
在选项对象中:
legendCallback: function(chart) {
var text = [];
text.push('<ul class="' + chart.id + '-legend">');
for (var i = 0; i < chart.data.datasets[0].data.length; i++) {
text.push('<li><span style="background-color:' +
chart.data.datasets[0].backgroundColor[i] + '">');
if (chart.data.labels[i]) {
text.push(chart.data.labels[i]);
}
text.push('</span></li>');
}
text.push('</ul>');
return text.join("");
}
Second, you need a container to insert the new html and using the method myChart.generateLegend()to get the customized html:
其次,您需要一个容器来插入新的 html 并使用myChart.generateLegend()方法来获取自定义的 html:
$("#your-legend-container").html(myChart.generateLegend());
After that, if you need, track down the events:
之后,如果需要,请跟踪事件:
$("#your-legend-container").on('click', "li", function() {
myChart.data.datasets[0].data[$(this).index()] += 50;
myChart.update();
console.log('legend: ' + data.datasets[0].data[$(this).index()]);
});
$('#myChart').on('click', function(evt) {
var activePoints = myChart.getElementsAtEvent(evt);
var firstPoint = activePoints[0];
if (firstPoint !== undefined) {
console.log('canvas: ' +
data.datasets[firstPoint._datasetIndex].data[firstPoint._index]);
}
else {
myChart.data.labels.push("New");
myChart.data.datasets[0].data.push(100);
myChart.data.datasets[0].backgroundColor.push("red");
myChart.options.animation.animateRotate = false;
myChart.options.animation.animateScale = false;
myChart.update();
$("#your-legend-container").html(myChart.generateLegend());
}
}
Another solution that I found, if you don't need to change the HTMl structure inside the legend, you can just insert the same HTML in your legend container and customize it by CSS, check this another link:
我发现的另一个解决方案,如果您不需要更改图例中的 HTMl 结构,您只需在图例容器中插入相同的 HTML 并通过 CSS 对其进行自定义,请查看另一个链接:
Hope it works for you.
希望对你有效。
回答by Jakub Juszczak
You can extract the legend markup.
您可以提取图例标记。
data () {
return {
legendMarkup: ''
}
},
ready () {
this.legendMarkup = this._chart.generateLegend()
}
And in your template you can output it.
在您的模板中,您可以输出它。
<div class="legend" ref="legend" v-html="legendMarkup"></div>
this._chart is the internal chartjs instance in vue-chartjs. So you can call all chartjs methods which are not exposed by vue-chartjs api over it.
this._chart 是 vue-chartjs 中的内部 chartjs 实例。因此,您可以通过它调用 vue-chartjs api 未公开的所有 chartjs 方法。
However you can also use the legend generator. The usage is the same in vue. You can pass in the options, use callbacks etc.
但是,您也可以使用图例生成器。用法与vue中相同。您可以传入选项,使用回调等。
回答by Farhad Azarbarzinniaz
please check this documentation.
请检查此文档。
Legend Configuration
图例配置
The chart legend displays data about the datasets that area appearing on the chart.
图表图例显示有关出现在图表上的区域的数据集的数据。
Configuration options Position of the legend. Options are:
配置选项 图例的位置。选项是:
'top' 'left' 'bottom' 'right'
“上”“左”“下”“右”
Legend Item Interface
图例物品界面
Items passed to the legend onClick function are the ones returned from labels.generateLabels. These items must implement the following interface.
传递给图例 onClick 函数的项目是从 labels.generateLabels 返回的项目。这些项目必须实现以下接口。
{
// Label that will be displayed
text: String,
// Fill style of the legend box
fillStyle: Color,
// If true, this item represents a hidden dataset. Label will be rendered with a strike-through effect
hidden: Boolean,
// For box border. See https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D/lineCap
lineCap: String,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/setLineDash
lineDash: Array[Number],
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineDashOffset
lineDashOffset: Number,
// For box border. See https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/lineJoin
lineJoin: String,
// Width of box border
lineWidth: Number,
// Stroke style of the legend box
strokeStyle: Color
// Point style of the legend box (only used if usePointStyle is true)
pointStyle: String
}
Example
例子
The following example will create a chart with the legend enabled and turn all of the text red in color.
以下示例将创建一个启用图例的图表并将所有文本颜色变为红色。
var chart = new Chart(ctx, { type: 'bar', data: data, options: { legend: { display: true, labels: { fontColor: 'rgb(255, 99, 132)' } } } }); Custom On Click Actions
var chart = new Chart(ctx, { type: 'bar', data: data, options: { legend: { display: true, labels: { fontColor: 'rgb(255, 99, 132)' } } } }); 自定义点击操作
It can be common to want to trigger different behaviour when clicking an item in the legend. This can be easily achieved using a callback in the config object.
单击图例中的项目时,通常希望触发不同的行为。这可以使用配置对象中的回调轻松实现。
The default legend click handler is:
默认的图例点击处理程序是:
function(e, legendItem) {
var index = legendItem.datasetIndex;
var ci = this.chart;
var meta = ci.getDatasetMeta(index);
// See controller.isDatasetVisible comment
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
// We hid a dataset ... rerender the chart
ci.update();
}
Lets say we wanted instead to link the display of the first two datasets. We could change the click handler accordingly.
var defaultLegendClickHandler = Chart.defaults.global.legend.onClick;
var newLegendClickHandler = function (e, legendItem) {
var index = legendItem.datasetIndex;
if (index > 1) {
// Do the original logic
defaultLegendClickHandler(e, legendItem);
} else {
let ci = this.chart;
[ci.getDatasetMeta(0),
ci.getDatasetMeta(1)].forEach(function(meta) {
meta.hidden = meta.hidden === null? !ci.data.datasets[index].hidden : null;
});
ci.update();
}
};
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
}
}
});
Now when you click the legend in this chart, the visibility of the first two datasets will be linked together.
现在,当您单击此图表中的图例时,前两个数据集的可见性将链接在一起。
HTML Legends
HTML 图例
Sometimes you need a very complex legend. In these cases, it makes sense to generate an HTML legend. Charts provide a generateLegend() method on their prototype that returns an HTML string for the legend.
有时您需要一个非常复杂的图例。在这些情况下,生成 HTML 图例是有意义的。图表在其原型上提供了一个 generateLegend() 方法,该方法返回图例的 HTML 字符串。
To configure how this legend is generated, you can change the legendCallback config property.
要配置此图例的生成方式,您可以更改 legendCallback 配置属性。
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legendCallback: function(chart) {
// Return the HTML string here.
}
}
});

