2014-12-02 66 views
0

所以我做了一些代码来绘制散点图,其中x轴上的每个刻度都是基因名称。这一切工作正常。我想要的是用户点击任何基因名称将被带到一个有关它的信息页面。更明确地说,我希望在鼠标悬停的标签后面出现一个矩形(或某种形状),并将该形状(以及文本本身)用作外部网页的链接。如何在图形上的x轴标签文本后面添加元素?

由于轴是由D3本身创建的,我不能将text对象更改为a具有链接属性的对象(或者我可以吗?),所以不知何故我需要向轴对象添加一堆子对象,之前文本对象,所以他们被绘制在后面,有能力成为链接。下面是我的一些代码,其中x轴实际创建(正常工作):

chart.append("g") 
    .attr("class", "x axis") 
    .attr("transform", "translate(0," + height + ")") 
    .call(xAxis) 
    .selectAll("text") 
     .style("text-anchor", "end") 
     .attr("dx", "-.8em") 
     .attr("dy", ".15em") 
     .attr("transform", function(d) { return "rotate(-65)" }); 

我已经尝试了一些不同的东西,最近:

d3.select(".x").data(genenames) 
    .insert("rect", "text") 
    .attr("x", function(d) { return x(d); }) 
    .attr("y", height) 
    .attr("width", "20") 
    .attr("height", "10") 
    .style("fill", "blue"); 

但浏览器抱怨:Uncaught NotFoundError: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.这是关于.insert我认为的事。我仍在学习JavaScript,所以也许有一些明显的我做错了,但我无法弄清楚这一点。任何帮助将非常感激。

回答

1

您正在选择轴g,我认为您需要剔号g s。

如何:

var genenames = ["One","Two","Three","Four"]  

d3.selectAll(".tick").data(genenames) 
    .insert("rect", "text") 
    .attr("x", 0) 
    .attr("y", height) 
    .attr("width", "20") 
    .attr("height", "10") 
    .style("fill", "blue"); 

here

+0

啊对了,谢谢。虽然有一个怪癖;如果我设置'.attr(“y”,height)'矩形不显示(或者它们离开底部的屏幕)。我改为使用与文本对象相同的y值,它恰好是9,并且一切正常。谢谢! – DaveTheScientist 2014-12-04 17:38:12