如何在图形上的 x 轴标签文本后面添加元素

How do I add an element behind the x-axis label text on a graph?

本文关键字:文本 标签 元素 添加 图形      更新时间:2023-09-26

所以我做了一些代码来绘制一个散点图,其中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,所以也许我做错了一些明显的事情,但我无法弄清楚这一点。任何帮助将不胜感激。

您正在选择轴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");

这里的例子。