[英]d3 - label placement for a nested pie chart
我想放置與下圖所示類似的標簽。 對於這種情況,這可能是2個問題,對不起。
嘗試了兩種不同的方法。
不合適的一個,從一個圓圈開始,獨立地繪制每個段,並依賴於數據的排序方式和標記parent
的屬性來標識塊(主/更大段)中的段。 這樣,我就不能根據主要部分在圓圈中的位置輕松放置標簽,並且數據感覺不自然。
https://jsfiddle.net/raven0us/c2jtsv4m/
一個更合適的一個,有塊(主要部分)和內部塊作為孩子,這樣,我可以使用centroid
並相應地放置標簽。 事情似乎很自然,但我無法弄清楚如何在主要細分中繪制多個內部細分,因此它看起來像我之前嘗試的圖表。
https://jsfiddle.net/raven0us/1v9mtdjL/
在每個腳本的開頭console.log(data)
,在colors
數組之前console.log(data)
以查看我想要說明的數據的確切結構。
您已經擁有的布局依賴於您的數據是統一的,這在現實世界中不會發生,所以我找到了一個數據集並用它來創建一個不需要完美數據的餅圖。
它是第一和第二個圖表的混合。 我已經在代碼中添加了大量的注釋,因此請仔細查看並檢查您是否了解正在發生的事情。 我在https://bl.ocks.org/ialarmedalien/1e453ed9b148be442f50e06ad7eb3759上放了一個演示,所以你可以在那里看到數據輸入。
function chart(id) {
// this reads in the CSV file
d3.csv('morley3.csv').then( data => {
// this massages the data I'm using into a more suitable form for your chart
// we have 12 runs with 6 experiments in each.
// each datum is of the form
// { Run: <number>, Expt: <number>, Speed: <number> }
const filteredData = data
.filter( d => d.Run < 13 )
.map( d => { return { Run: +d.Run, Expt: +d.Expt, Speed: +d.Speed } } )
// set up the chart
const width = 800,
height = 800,
radius = Math.min(height, width) * 0.5 - 100,
// how far away from the chart the labels should be
labelOffset = 10,
svg = d3.select(id).append("svg")
.attr("width", width)
.attr("height", height),
g = svg.append("g")
.attr("transform", `translate(${width/2}, ${height/2})`),
// this will be used to generate the pie segments
arc = d3.arc()
.outerRadius(radius)
.innerRadius(0),
// group the data by the run number
// this results in 12 groups of six experiments
// the nested data has the form
// [ { key: <run #>, values: [{ Run: 1, Expt: 1, Speed: 958 }, { Run: 1, Expt: 2, Speed: 869 } ... ],
// { key: 2, values: [{ Run: 2, Expt: 1, Speed: 987 },{ Run: 2, Expt: 2, Speed: 809 } ... ],
// etc.
nested = d3.nest()
.key( d => +d.Run )
.entries(filteredData),
chunkSize = nested[0].values.length,
// d3.pie() is the pie chart generator
pie = d3.pie()
// the size of each slice will be the sum of all the Speed values for each run
.value( d => d3.sum( d.values, function (e) { return e.Speed } ) )
// sort by run #
.sort( (a,b) => a.key - b.key )
(nested)
// bind the data to the DOM. Add a `g` for each run
const runs = g.selectAll(".run")
.data(pie, d => d.key )
.enter()
.append("g")
.classed('run', true)
.each( d => {
// run the pie generator on the children
// d.data.values is all the experiments in the run, or in pie terms,
// all the experiments in this piece of the pie. We're going to use
// `startAngle` and `endAngle` to specify that we're only generating
// part of the pie. The values for `startAngle` and `endAngle` come
// from using the pie chart generator on the run data.
d.children = d3.pie()
.value( e => e.Speed )
.sort( (a,b) => a.Expt - b.Expt )
.startAngle( d.startAngle )
.endAngle( d.endAngle )
( d.data.values )
})
// we want to label each run (rather than every single segment), so
// the labels get added next.
runs.append('text')
.classed('label', true)
// if the midpoint of the segment is on the right of the pie, set the
// text anchor to be at the start. If it is on the left, set the text anchor
// to the end.
.attr('text-anchor', d => {
d.midPt = (0.5 * (d.startAngle + d.endAngle))
return d.midPt < Math.PI ? 'start' : 'end'
} )
// to calculate the position of the label, I've taken the mid point of the
// start and end angles for the segment. I've then used d3.pointRadial to
// convert the angle (in radians) and the distance from the centre of
// the circle/pie (pie radius + labelOffset) into cartesian coordinates.
// d3.pointRadial returns [x, y] coordinates
.attr('x', d => d3.pointRadial( d.midPt, radius + labelOffset )[0] )
.attr('y', d => d3.pointRadial( d.midPt, radius + labelOffset )[1] )
// If the segment is in the upper half of the pie, move the text up a bit
// so that the label doesn't encroach on the pie itself
.attr('dy', d => {
let dy = 0.35;
if ( d.midPt < 0.5 * Math.PI || d.midPt > 1.5 * Math.PI ) {
dy -= 3.0;
}
return dy + 'em'
})
.text( d => {
return 'Run ' + d.data.key + ', experiments 1 - 6'
})
.call(wrap, 50)
// now we can get on to generating the sub segments within each main segment.
// add another g for each experiment
const expts = runs.selectAll('.expt')
// we already have the data bound to the DOM, but we want the d.children,
// which has the layout information from the pie chart generator
.data( d => d.children )
.enter()
.append('g')
.classed('expt', true)
// add the paths for each sub-segment
expts.append('path')
.classed('speed-segment', true)
.attr('d', arc)
// I simplified this slightly to use one of the built-in d3 colour schemes
// my data was already numeric so it was easy to use the run # as the colour
.attr('fill', (d,i) => {
const c = i / chunkSize,
color = d3.rgb( d3.schemeSet3[ d.data.Run - 1 ] );
return c < 1 ? color.brighter(c*0.5) : color;
})
// add a title element that appears when mousing over the segment
.append('title')
.text(d => 'Run ' + d.data.Run + ', experiment ' + d.data.Expt + ', speed: ' + d.data.Speed )
// add the lines
expts.append('line')
.attr('y2', radius)
// assign a class to each line so we can control the stroke, etc., using css
.attr('class', d => {
return 'run-' + d.data.Run + ' expt-' + d.data.Expt
})
// convert the angle from radians to degrees
.attr("transform", d => {
return "rotate(" + (180 + d.endAngle * 180 / Math.PI) + ")";
});
function wrap(text, width) {
text.each(function () {
let text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.2, // ems
tfrm = text.attr('transform')
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan")
.attr("x", x)
.attr("y", y)
.attr("dy", ++lineNumber * lineHeight + dy + "em")
.text(word);
}
}
});
}
return svg;
})
}
chart('#chart');
我不確定我是否理解這個問題。 但這太長了,不能插入評論,所以我寫了一個答案,也許它解決了問題。
第一種方法的陳述問題是:
這樣,我就不能根據主要部分在圓圈中的位置輕松放置標簽
標簽放置代碼是:
labels.selectAll("text")
.data(keys)
.enter()
.append("text")
.style("text-anchor", "middle")
.style("font-weight", "bold")
//LABEL PLACEMENT CODE
.attr("x", (d, i) => {
return barScale(config.max * 1.2) * Math.cos(segmentSlice * i - Math.PI / 2);
})
.attr("y", (d, i) => {
return barScale(config.max * 1.2) * Math.sin(segmentSlice * i - Math.PI / 2);
})
這將標簽放在大段分割線上。 我們總共有12個段,每個段跨越30度。 每個大段有6個子段,每個子段跨越5度。 因此,您似乎只需要將標簽旋轉15度(3個子段跨度),將它們放置在問題中的圖片中。
首先將15度轉換為弧度:
15 * PI / 180 = 0.261799
然后將以上值添加到標簽放置代碼:
.attr("x", (d, i) => {
return barScale(config.max * 1.2) *
Math.cos(segmentSlice * i - Math.PI / 2 + 0.261799); //HERE
}).attr("y", (d, i) => {
return barScale(config.max * 1.2) *
Math.sin(segmentSlice * i - Math.PI / 2 + 0.261799); //AND HERE
})
這是更新的小提琴: https : //jsfiddle.net/fha19jtm/
並且所有標簽都像給定的圖片一樣放置。 data屬性還可用於根據大/小段的組合來改變旋轉角度。 這樣,每個標簽的放置可以精細到所需的量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.