[英]nvd3 piechart.js - How to edit the tooltip?
我正在使用nvd3的piechart.js组件在我的网站上生成一个饼图。 提供的.js文件包含几个var,如下所示:
var margin = {top: 30, right: 20, bottom: 20, left: 20}
, width = null
, height = null
, showLegend = true
, color = nv.utils.defaultColor()
, tooltips = true
, tooltip = function(key, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + '</p>'
}
, noData = "No Data Available."
, dispatch = d3.dispatch('tooltipShow', 'tooltipHide')
;
在我的内联js中,我已经能够覆盖其中一些变量,比如这样(覆盖showLegend和margin):
var chart = nv.models.pieChart()
.x(function(d) { return d.label })
.y(function(d) { return d.value })
.showLabels(false)
.showLegend(false)
.margin({top: 10, right: 0, bottom: 0, left: 0})
.donut(true);
我试过用同样的方法覆盖工具提示:
.tooltip(function(key, y, e, graph) { return 'Some String' })
但是当我这样做时,我的饼图根本不显示。 为什么我不能在这里覆盖工具提示? 还有其他方法吗? 我真的宁愿不必编辑piechart.js本身; 我需要保持该文件的通用性,以便在多个小部件中使用。
虽然我们在这里,有什么方法可以将整个工具提示变成可点击的链接吗?
只是以这种方式覆盖它肯定会工作
function tooltipContent(key, y, e, graph) {
return '<h3>' + key + '</h3>' +'<p>' + y + '</p>' ;
}
要么
tooltipContent(function(key, y, e, graph) { return 'Some String' })
我有同样的问题,使用nvd3 1.8.1,这是我找到的解决方案。
如果没有useInteractiveGuideline
选项,您只需在chart.tooltip.contentGenerator(function (d){ YOUR_FUNCTION_HERE})
声明工具提示生成函数:
参数d
在调用工具提示时由nvd3给出,它有三个属性:
value
:光标位置的x轴值 index
:图表的datum
与光标位置对应的索引 series
:包含图表中每个项目的数组:
key
:该项目的图例键 value
:光标位置处该项目的y轴值 color
:该项目的图例颜色 所以这里有一个例子:
chart.tooltip.contentGenerator(function (d) {
var html = "<h2>"+d.value+"</h2> <ul>";
d.series.forEach(function(elem){
html += "<li><h3 style='color:"+elem.color+"'>"
+elem.key+"</h3> : <b>"+elem.value+"</b></li>";
})
html += "</ul>"
return html;
})
重要的提示
当使用选项useInteractiveGuideline
, chart.tooltip
对象不用于生成工具提示,您必须改为使用chart.interactiveLayer.tooltip
,即:
this.chart.interactiveLayer.tooltip.contentGenerator(function (d) { ... })
我希望答案对你有用,即使很晚。
“useInteractiveGuideline”不能存在自定义工具提示。
如果您碰巧使用Angular NVD3包装器,设置自定义消息的方法是通过图表选项,只需:
$scope.options = {
chart: {
...
tooltip: {
contentGenerator: function(d) {
return d.series[0].key + ' ' + d.series[0].value;
}
},
...
}
};
要添加到先前的答案,有时您想要使用系列的数据,而不仅仅是x
和y
。 比如说什么时候
data = {'values': [{'month': 1, 'count': 2}, ...], 'key': 'test' }
对于那些情况,请使用
.tooltip(function(key, x, y, e, graph) {
var d = e.series.values[e.pointIndex];
return '<h3>' + e.series.key + '</h3><p>' + d.month.toString() + ...;
});
e.series
是鼠标悬停的特定系列, e.pointIndex
是系列值的索引。 这里是e.series.key == key
,但我过去常常同情e.series
。
my_chart = nv.models.multiBarChart()
.tooltip(function(key, x, y, e, graph) {
return '<h3>' + key + '</h3>' +
'<p>' + y + ' on ' + x + '</p>';
});
我认为你在工具提示功能中缺少'x'参数。 函数调用的格式为:
function(key, x, y, e, graph)
var chart = nv.models.multiBarChart();
chart.tooltip.contentGenerator(function (obj) {
return JSON.stringify("<b>HOHO</b>")
})
这对我有用......
chart:{ interactive:true, tooltips: true, tooltip: { contentGenerator: function (d) { return '<h3>PUT YOUR DATA HERE Eg d.data.name</h3>' } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.