我有一个 c3.js 线图,表示 2 个值的演变。我需要将折线图的工具提示设置为饼图(工具提示 = 另一个 c3.js 图形)。
这是我成功的:
http://jsfiddle.net/owhxgaqm/80/
// c3 - custom tooltip
function generateGraph(data1,data2) {
console.log(data1.name + '\t' + data1.value + '\t' + data2.name + '\t' + data2.value);
var chart1 = c3.generate(
{
bindto: "#t",
data: {columns : [[data1.name, data1.value],[data2.name, data2.value]],
type : 'pie'}
});
}
var chart = c3.generate({
data: {
columns: [
['data1', 1000, 200, 150, 300, 200],
['data2', 400, 500, 250, 700, 300], ]
},
tooltip: {
contents: function (d, defaultTitleFormat, defaultValueFormat, color) {
generateGraph(d[0], d[1]);
var divt = document.getElementById("t");
return '';
}
}
});
如您所见,我将“工具提示”与现有的 div 绑定(bind)在一起,因此这并不是我真正想要的 c3.js 功能。
欢迎任何想法。
谢谢。
最佳答案
在 C3 工具提示中添加图表
您可以使用c3已有的工具提示元素。在您的内容函数中调用 generateGraph
函数(请参阅下一步)。除了数据之外,还传入 this.tooltip
中可用的工具提示元素。
...
tooltip: {
contents: function (d) {
// this creates a chart inside the tooltips
var content = generateGraph(this.tooltip, d[0], d[1])
// we don't return anything - see .html function below
}
}
...
您的generateGraph
函数基本上在您的工具提示元素中创建一个c3图表(bindto
支持d3元素)。我们做了一些优化(如果数据相同,则不会重新创建图表)和清理(重新创建图表时,它会被销毁并从 DOM 中删除)
function generateGraph(tooltip, data1, data2) {
// if the data is same as before don't regenrate the graph - this avoids flicker
if (tooltip.data1 &&
(tooltip.data1.name === data1.name) && (tooltip.data1.value === data1.value) &&
(tooltip.data2.name === data2.name) && (tooltip.data2.value === data2.value))
return;
tooltip.data1 = data1;
tooltip.data2 = data2;
// remove the existing chart
if (tooltip.chart) {
tooltip.chart = tooltip.chart.destroy();
tooltip.selectAll('*').remove();
}
// create new chart
tooltip.chart = c3.generate({
bindto: tooltip,
size: {
width: 200,
height: 200
},
data: {
columns: [[data1.name, data1.value], [data2.name, data2.value]],
type: 'pie'
}
});
// creating a chart on an element sets its position attribute to relative
// reset it to absolute (the tooltip was absolute originally) for proper positioning
tooltip.style('position', 'absolute');
}
请注意,我们设置了图表大小,使其更像工具提示内容而不是子图表。
最后一点有点 hacky - 因为 c3 要求我们设置一个 HTML(我们不想这样做),并且因为我们没有任何其他回调,所以我们可以轻松地在内容处理程序之后使用,我们必须禁用 c3 用于设置工具提示上的 html 内容的功能(这只会影响此图表的工具提示),即 .tooltip.html
// MONKEY PATCHING (MAY break if library updates change the code that sets tooltip content)
// we override the html function for the tooltip to not do anything (since we've already created the tooltip content inside it)
chart.internal.tooltip.html = function () {
// this needs to return the tooltip - it's used for positioning the tooltip
return chart.internal.tooltip;
}
fiddle - http://jsfiddle.net/muuqvf1a/
工具提示定位
除了使用 c3 的工具提示定位之外,您还可以在图表底部调整工具提示的大小和位置。只需样式 .c3-tooltip-container
。
替代方案
请注意,c3 还支持子图表 ( http://c3js.org/reference.html#subchart-show ) 和 data.mouseover
( http://c3js.org/reference.html#data-onmouseover ),这也可能是值得探索的更清晰的途径。
关于javascript - c3.js - c3 图表,有一个工具提示,里面有 c3 图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32348378/