2014-12-02 31 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