【问题标题】:Can't add title to stacked bar graph on D3无法在 D3 上为堆积条形图添加标题
【发布时间】:2017-01-30 02:10:25
【问题描述】:

我使用这个example 创建了一个堆积条形图。该图表可以工作并呈现,但我无法添加鼠标悬停标签。

我试过这个...

  DATE.selectAll("rect")
  .data(function(d) { return d.ages; })
  .enter().append("rect")
  .attr("width", x.rangeBand())
  .attr("y", function(d) { return y(d.y1); })
  .attr("height", function(d) { return y(d.y0) - y(d.y1); })
  .style("fill", function(d) { return color(d.name); });
  .append("svg:title")
  .text(functino(d){return "foo"});

但是在添加.append("svg:title... 之后,图形会停止渲染。如果我删除 .style("fill... 线,图形会呈现,但它没有堆叠,也没有鼠标悬停功能。

我也尝试过使用工具提示路由。 (Source)

  .on("mouseover", function() { tooltip.style("display", null); })
  .on("mouseout", function() { tooltip.style("display", "none"); })
  .on("mousemove", function(d) {
    var xPosition = d3.mouse(this)[0] - 15;
  var yPosition = d3.mouse(this)[1] - 25;
  tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
tooltip.select("text").text(d.y);
});


// Prep the tooltip bits, initial display is hidden
var tooltip = svg.append("g")
.attr("class", "tooltip")
.style("display", "none");

tooltip.append("rect")
.attr("width", 30)
.attr("height", 20)
.attr("fill", "white")
.style("opacity", 0.5);

tooltip.append("text")
.attr("x", 15)
.attr("dy", "1.2em")
.style("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "bold");

但还是不走运。有我需要加载的库吗?不知道发生了什么。

【问题讨论】:

    标签: d3.js tooltip bar-chart stacked-chart


    【解决方案1】:

    当您尝试附加 title 时,图表会停止呈现,因为您有错字:它是 function,而不是 functino

    除此之外,这是您获取每个堆叠条的值所需的:

    .append("title")
    .text(function(d){
        return d[1]-d[0]
    });
    

    这里是演示:https://bl.ocks.org/anonymous/raw/886d1749c4e01e191b94df23d97dcaf7/

    但我不喜欢<title>s。它们不是很通用。因此,我更喜欢创建一个 div,而不是像您链接的第二个代码那样创建另一个 <text>

    var tooltip = d3.select("body").append("div")
        .attr("class", "tooltip")
        .style("opacity", 0);
    

    我们以这种方式定位和设置 HTML 文本:

    .on("mousemove", function(d) {
        tooltip.html("Value: " + (d[1] - d[0]))
            .style('top', d3.event.pageY - 10 + 'px')
            .style('left', d3.event.pageX + 10 + 'px')
            .style("opacity", 0.9);
    }).on("mouseout", function() {
        tooltip.style("opacity", 0)
    });
    

    这里是演示:https://bl.ocks.org/anonymous/raw/f6294c4d8513dbbd8152770e0750efd9/

    【讨论】:

    • 哇!两者都有效,但我同意你的看法。 div 路线要好得多。谢谢杰拉尔多!
    猜你喜欢
    • 2019-06-19
    • 2013-12-22
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2016-10-13
    • 2013-09-15
    • 1970-01-01
    • 2018-12-18
    相关资源
    最近更新 更多