Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

javascript - 旋转dc.js饼图中的饼图标签(Rotate Pie Label in dc.js Pie Chart)

在此处输入图片说明 Let's say I have the following code in dc.js to create a pie chart:(假设我在dc.js中有以下代码来创建饼图:)

var chart = dc.pieChart("#test"); d3.csv("morley.csv", function(error, experiments) { var ndx = crossfilter(experiments), runDimension = ndx.dimension(function(d) {return "run-"+d.Run;}) speedSumGroup = runDimension.group().reduceSum(function(d) {return d.Speed * d.Run;}); chart .width(768) .height(480) .slicesCap(4) .innerRadius(100) .dimension(runDimension) .group(speedSumGroup) .legend(dc.legend()) // workaround for #703: not enough data is accessible through .label() to display percentages .on('pretransition', function(chart) { chart.selectAll('text.pie-slice').text(function(d) { return d.data.key + ' ' + dc.utils.printSingleValue((d.endAngle - d.startAngle) / (2*Math.PI) * 100) + '%'; }) }); chart.render(); }); What I want to do is rotate the label, but when I do so, all of the labels translate to the center of the pie.(我想做的是旋转标签,但是当我旋转时,所有标签都平移到饼图的中心。) chart.renderlet(function (chart) { chart.selectAll('text.pie-slice') .attr('transform', 'rotate(315)'); }); Is there a way to rotate the labels without changing their position on the graph?(有没有一种方法可以旋转标签而不更改其在图形上的位置?)   ask by Sledge translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem is that you're replacing the transform attribute for these elements, which is currently used to "translate" the labels in position.(问题是您要替换这些元素的transform属性,该属性当前用于“翻译”适当位置的标签。)

Since it's hard to dig into the calculations used here, I think the best approach is to pull the existing transform attribute and modify it, like this:(由于很难深入研究此处使用的计算,我认为最好的方法是提取现有的transform属性并对其进行修改,如下所示:) chart.on('renderlet', function (chart) { chart.selectAll('text.pie-slice') .attr('transform', function(d) { var translate = d3.select(this).attr('transform'); var ang = ((d.startAngle + d.endAngle) / 2 * 180 / Math.PI)%360; if(ang<180) ang -= 90; else ang += 90; return translate + ' rotate(' + ang + ')'; }); }); For my own entertainment, I've also rotated the labels using the start and end angles of the pie slices.(作为我自己的娱乐,我还使用饼图的开始和结束角度旋转了标签。) It's unfortunate you can't do this as a pretransition event and avoid the "jump".(不幸的是,您不能将其作为过渡前的事件来避免“跳跃”。) It will just get overwritten by the animations.(它将被动画覆盖。) Doing this properly would require some changes to dc.js - file an issue if you're interested.(正确执行此操作将需要对dc.js进行一些更改-如果您有兴趣,请提交问题 。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...