我正在使用nvd3构建一个饼图,并且无法弄清楚当用户将鼠标悬停在切片上时如何使标题动态化或至少运行回调。
这是我的代码的相关部分:
nv.addGraph(function () {
let chart : any = nv.models.pieChart()
.x(function (d : any) {
return d.label;
})
.y(function (d : any) {
return d.value;
})
.showLabels(false)
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.6) //Configure how big you want the donut hole size to be.
.showLegend(false)
.color(function (d : any) {
return d.data.color;
})
.width(300)
.height(300)
.title("Hello");
//.on("mouseover", function(d: any) { console.log(d); });
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
该图表完全按预期工作。
这是图表的getFields()。由于某种原因,颜色不起作用,但在我自己的网站上它可以工作。
答案 0 :(得分:2)
您可以使用NVD3库的dispatch
方法进行事件订阅,当然,您可以使用任何本机d3方法,例如d3.select
。只需将其添加到您的代码中:
chart.pie.dispatch.on('elementMouseover', function(e) {
d3.select('.nv-pie-title').text(e.label);
});
chart.pie.dispatch.on('elementMouseout', function(e) {
d3.select('.nv-pie-title').text("Hello");
});
检查以下隐藏代码段中的工作演示:
nv.addGraph(function() {
let chart = nv.models.pieChart()
.x(function(d) {
return d.label;
})
.y(function(d) {
return d.value;
})
.showLabels(false)
.labelThreshold(.05) //Configure the minimum slice size for labels to show up
.labelType("percent") //Configure what type of data to show in the label. Can be "key", "value" or "percent"
.donut(true) //Turn on Donut mode. Makes pie chart look tasty!
.donutRatio(0.6) //Configure how big you want the donut hole size to be.
.showLegend(false)
.color(function(d) {
return d.data.color;
})
.width(300)
.height(300)
.title("Hello");
//.on("mouseover", function(d: any) { console.log(d); });
chart.pie.dispatch.on('elementMouseover', function(e) {
d3.select('.nv-pie-title').text(e.label);
});
chart.pie.dispatch.on('elementMouseout', function(e) {
d3.select('.nv-pie-title').text("Hello");
});
d3.select("#chart svg")
.datum(exampleData())
.transition().duration(350)
.call(chart);
return chart;
});
function exampleData() {
return [{
label: "timeout",
value: "14.2",
data: {
"color": "#f00"
}
}, {
label: "uncontacted",
value: "78.8",
data: {
"color": "#999999"
}
}, {
label: "refused",
value: "6.9",
data: {
"color": "#FFFFFF"
}
}];
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.6/nv.d3.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.7.0/nv.d3.min.js"></script>
<div id="chart">
<svg style="height: 300px; margin: -20px 0;"></svg>
</div>
&#13;