简体   繁体   English

使用Chart.js自定义标签

[英]Custom Labels with Chart.js

Looking through the advanced tooltips and legend configuration for chart.js, I am not sure how to achieve the following label style for my charts. 通过查看chart.js的高级工具提示图例配置 ,我不确定如何为我的图表实现以下标签样式。

在此输入图像描述

How can I output my numbers for each section of this donut chart and connect those numbers to each segment of the chart? 如何输出此圆环图的每个部分的数字并将这些数字连接到图表的每个部分?

If it's not possible with Chart.js, then can anyone point me to a chart library that will allow me to do this? 如果Chart.js无法实现,那么任何人都可以指向一个允许我这样做的图表库吗?

 new Chart(document.querySelector('#chart'), { type: 'doughnut', data: { labels: [ 'Red', 'Blue', 'Yellow' ], datasets: [{ data: [300, 50, 100], backgroundColor: [ '#FF6384', '#36A2EB', '#FFCE56' ], hoverBackgroundColor: [ '#FF6384', '#36A2EB', '#FFCE56' ] }] }, options: { legend: { display: false } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.min.js"></script> <canvas id="chart" width="400" height="400"/> 

I find that chartjs is difficult to work with (but it's nice in a pinch). 我发现chartjs很难处理(但是它很好用)。 You could try D3, which is highly customisable. 您可以尝试D3,它是高度可定制的。 It creates charts using svgs instead of canvas so the elements are a easier to access and work with. 它使用svgs而不是canvas创建图表,因此元素更易于访问和使用。

Here's the code, but it won't run in situ as it requires an external CSV file with the data, and a webserver to prevent CORs errors. 这是代码,但它不会在原地运行,因为它需要带有数据的外部CSV文件,以及防止CORs错误的Web服务器。 Here's the CSV for your data (data.csv): 这是您的数据的CSV(data.csv):

percentage_label,percentage
19,19
10,10
32,32
39,39

 var width = 960, height = 500, radius = Math.min(width, height) / 2; var color = d3.scale.ordinal() .range(["#fdb92e", "#c02f8e", "#1aaaa9", "#ffffff"]); var arc = d3.svg.arc() .outerRadius(radius - 70) .innerRadius(radius - 180); var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.population; }); var svg = d3.select("body").append("svg") .attr("width", width) .attr("height", height) .append("g") .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")"); d3.csv("data.csv", type, function(error, data) { if (error) throw error; var g = svg.selectAll(".arc") .data(pie(data)) .enter().append("g") .attr("class", "arc"); g.append("path") .attr("d", arc) .style("fill", function(d) { return color(d.data.percentage_label); }) .style("stroke-width","0px"); g.append("text") .attr("transform", function(d) { return "translate(" + ( (radius + 30) * Math.sin( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ) + ", " + ( -1 * (radius - 10) * Math.cos( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ) +")";}) .attr("dy", ".5em") .style("fill","#ffffff") .style("font-size","40px") .text(function(d) { return (d.data.percentage_label + "%"); }); g.append("circle") .attr("transform", function(d) {return "translate(" + arc.centroid(d) + ")";}) .attr("r", 5) .style("fill","#ffffff"); g.append("circle") .attr("transform", function(d) {return "translate(" + ( (radius - 20) * Math.sin( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ) + ", " + ( -1 * (radius - 50) * Math.cos( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ) +")";}) .attr("r", 5) .style("fill","#ffffff"); function lineCoordinates(d,x) { /* x: coordinate to return */ //not the most efficient method var pa = []; var p1 = arc.centroid(d); pa.push(p1[0]); pa.push(p1[1]); pa.push( (radius - 20) * Math.sin( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ); pa.push( -1 * (radius - 50) * Math.cos( ((d.endAngle - d.startAngle) / 2) + d.startAngle ) ); return pa[x]; } g.append("line") .style("stroke","white") .style("stroke-width","2px") .attr("x1",function(d) { return lineCoordinates(d,0);}) .attr("y1", function(d) { return lineCoordinates(d,1);}) .attr("x2", function(d) { return lineCoordinates(d,2);}) .attr("y2", function(d) { return lineCoordinates(d,3);}); }); function type(d) { d.population = +d.percentage_label; return d; } 
 body { background-color: #F68135; } .arc text { font: 10px sans-serif; text-anchor: middle; } .arc path { stroke: #fff; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script> 

My result is fairly close: 我的结果相当接近:

在此输入图像描述

Here are the modifications I made to the basic D3 doughnut chart (based on this example: https://bl.ocks.org/mbostock/3887193 ): 以下是我对基本D3圆环图进行的修改(基于此示例: https//bl.ocks.org/mbostock/3887193 ):

  • changed inner and out radiuses (radii?) 改变了内半径和半径(半径?)
  • changed colours (this is the scale.ordinal part) 改变颜色(这是scale.ordinal部分)
  • added styles for the labels 为标签添加了样式
  • moved the labels out from the centers of the segments (as there is some arc math involved, this was helpful: Label outside arc (Pie chart) d3.js ) 将标签从段的中心移出(因为涉及一些弧数学,这很有帮助: 弧外标签(饼图)d3.js
  • added a pair of circles for the endpoints of the callout lines 为标注线的端点添加了一对圆圈
  • added lines for the callouts 为标注添加了行
  • added a small function (lineCoordinates) to make the positioning math a little easier to deal with 添加了一个小函数(lineCoordinates),使定位数学更容易处理

I'm sure this could all be trimmed up and made a little more efficient. 我相信这一切都可以整理并提高效率。 I'd also recommend making the segment colours different from the label/callout colours (that one callout get's lost on the last segment). 我还建议使分段颜色与标签/标注颜色不同(一个标注在最后一个分段上丢失)。

I don't have the same label font, but because this is done using SVGs you can easily change the font with styles. 我没有相同的标签字体,但因为这是使用SVG完成的,所以您可以轻松地使用样式更改字体。 That's not the case with Chartjs (I ran into the same problem when I tried to modify label styles in Chartjs). Chartjs的情况并非如此(当我尝试修改Chartjs中的标签样式时遇到了同样的问题)。

D3 has a steeper learning curve than Chartjs, but once you get the hang of it, you can do pretty much anything graph related with it.Official site is here https://d3js.org/ D3比Chartjs有更陡峭的学习曲线,但是一旦掌握了它,你几乎可以做任何与之相关的图形。官方网站就在这里https://d3js.org/

Custom positioning of individual point labels is possible with Charts.js Data Labels Plugin. 使用Charts.js数据标签插件可以自定义各个点标签。

Source : https://github.com/chartjs/chartjs-plugin-datalabels 资料来源https//github.com/chartjs/chartjs-plugin-datalabels

The radial positioning is illustrated here: https://chartjs-plugin-datalabels.netlify.com/guide/positioning.html 径向定位如下所示: https//chartjs-plugin-datalabels.netlify.com/guide/positioning.html

定位示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM