从图例中选择文本时,如何选择切片。我也想在点击切片内的标签时触发click事件。
我尝试检查图例的键是否相同,但无法使其起作用。我不知道如何做到这一点,也许是在一个班级上,然后更改班级,但是我还是要检查每个切片是否与图例相同,但这是行不通的。
pieChart = () => {
// set the dimensions and margins of the graph
let width = 800;
let height = 450
let margin = 40
let radius = Math.min(width, height) / 2 - margin
let svg = d3.select('#my_dataviz')
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
// Create dummy data
const slices = [{
color: 'blue',
descripcion: 'zepe',
cantidad: '100'
},
{
color: 'grey',
descripcion: 'duan',
cantidad: '25'
},
{
color: 'pink',
descripcion: 'auan',
cantidad: '25'
},
{
color: 'green',
descripcion: 'buan',
cantidad: '40'
}
];
let data = [];
slices.forEach(cantidad => {
data.push([cantidad.cantidad, cantidad.descripcion])
})
var color = d3.scaleOrdinal()
.domain(data)
.range(d3.schemeSet2);
var pie = d3.pie()
.value(function(d) {
return d.value[0];
})
var data_ready = pie(d3.entries(data))
let arcGenerator = d3.arc()
.innerRadius(0)
.outerRadius(radius)
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('path')
.attr('d', arcGenerator)
.attr('fill', function(d) {
return (color(d.data.key))
})
.attr("stroke", "black")
.attr("stroke-dasharray", "2,2,4,2,6,2,4,2")
.on("click", Clickar)
.style("stroke-width", "1px")
.style("opacity", 0.7)
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('text')
.text(function(d) {
return d.data.value[1]
})
.attr("transform", function(d, i) {
return "translate(" + (radius + 75) + ',' + (-radius + 15 + (d.index * 30)) + ")";
})
.attr('fill', function(d) {
return (color(d.data.key))
})
.style("text-anchor", "middle")
.style("font-size", 17)
.on("click", Clickar)
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('rect')
.attr('x', radius + 30)
.attr('y', function(d, i) {
return -radius + (d.index * 30)
})
.attr('width', '20')
.attr('height', '20')
.attr('fill', function(d) {
return (color(d.data.key))
})
.attr("stroke", "black")
.style('stroke-width', '1px')
svg
.selectAll('mySlices')
.data(data_ready)
.enter()
.append('text')
.text(function(d) {
return d.data.value[1]
})
.attr("transform", function(d) {
return "translate(" + arcGenerator.centroid(d) + ")";
})
.style("text-anchor", "middle")
.style("font-size", 17)
.on("click", Clickar)
function Clickar(e, data) {
if (d3.select(this).attr('d')) {
if (d3.select(this).style('stroke-width') === "1px") {
d3
.select(this)
.attr('d', d3.arc().innerRadius(0).outerRadius(radius + 20))
.style('stroke-width', '2px')
} else {
d3.select(this)
.attr('stroke', 'black')
.style("stroke-width", "1px")
.attr('d', arcGenerator)
}
}
}
}
pieChart()
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id="my_dataviz"></div>