这个问题的动机是基于我之前的question关于绘制散点图和词云。 Jason Davies 的 wordcloud 不知为何对我不起作用,所以我用纯 jQuery wordcloud 替换了它 - jQCloud .
应用程序的目标保持不变。当我浏览散点图上的点时,应该会出现词云。我有两个问题:
- 加载页面后,我应该重复该点两次以渲染词云。我不知道为什么。
- 在当前设置中,当调用
mouseout
事件时,词云不会隐藏。如何修复?
任何想法都值得赞赏。代码粘贴在下面以及JSFiddle上.
$(document).ready(function() {
var data = [[5,3,[{'text':'word1','weight':4},{'text':'word2','weight':10}]],
[3,5,[{'text':'word3','weight':5},{'text':'word4','weight':4}]],
[1,4,[{'text':'word1','weight':3},{'text':'word2','weight':5},{'text':'word3','weight':2}]],
[2,3,[{'text':'word2','weight':1},{'text':'word3','weight':5}]]];
var margin = {top: 20, right: 15, bottom: 60, left: 60},
width = 500 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[0]; })])
.range([ 0, width ]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([ height, 0 ]);
var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// Draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
var g = main.append("svg:g");
var circle = g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return x(d[0]); } )
.attr("cy", function (d) { return y(d[1]); } )
.attr("r", 5);
// FUNCTION TO DISPLAY WORDCLOUD
circle.on('mouseover', function(d){
div.style("display", "block")
$("#my_words").jQCloud('update',d[2]);
});
circle.on('mouseout', function(){
div.style("display", "none")
div.select("svg").remove();
});
var div = d3.select("body")
.append("div")
.style("display", "none");
});
最佳答案
您正在使用 jCloud 的“更新”功能,我无法找到该功能的文档。如果您仅在云已填充时调用“更新”,则一切都会正常:
var cloudInitialized = false; // FUNCTION TO DISPLAY WORDCLOUD circle.on('mouseover', function(d){ d3.selectAll("#my_words span").style("display", "inline"); if (cloudInitialized) $("#my_words").jQCloud("update", d[2]); else $("#my_words").jQCloud(d[2]); cloudInitialized = true; });
您在代码中隐藏了一个不同 div(一种工具提示,而不是文字云)。
关于javascript - 将 d3.js 与 jquery 函数调用结合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40204295/