【问题标题】:How to display value labels above graph bars?如何在图形条上方显示值标签?
【发布时间】:2013-03-12 18:05:46
【问题描述】:

有没有办法在此图表的条形上方显示值?我有从 TSV 中检索的值,但目前难以将条形值显示为每个相应条形上方的标签。

这是我作为 TSV 拥有的数据:

这是我目前用于渲染图表的内容:

margin =
top: 30
right: 30
bottom: 40
left: 60
width = 960 - margin.left - margin.right
height = 500 - margin.top - margin.bottom

formatPercent = d3.format("")

x = d3.scale.ordinal()
    .rangeRoundBands([width, 0], .1)

y = d3.scale.linear()
    .range([height, 0])

xAxis = d3.svg.axis()
    .scale(x)
    .orient("bottom")
    .tickFormat(formatPercent)

yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(formatPercent)

svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")")

d3.tsv("/Home/GetTsv/data.tsv", (error, data)->

    data.forEach((d)->
        d.Total = +d.Total
    )

    x.domain(data.map((d)-> d.Year))
    y.domain([0, d3.max(data, (d)-> d.Total)])

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .append("text")
        .attr("y", 30)
        .attr("x", width / 2)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Year")

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", -60)
        .attr("x", -(height / 2))
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Total Activity")

    svg.selectAll(".bar")
        .data(data)
        .enter().append("rect")
        .attr("class", "bar")
        .attr("x", (d)-> x(d.Year))
        .attr("width", x.rangeBand())
        .attr("y", (d)-> y(d.Total))
        .attr("height", (d)-> height - y(d.Total))

#   svg.selectAll("text")
#       .data(data)
#       .enter()
#       .append("text")
#       .text((d)-> d.Total)
#       .attr("x", (d, i)-> i * (width / data.length))
#       .attr("y", (d)-> height - d)

)

这是我的图表的样子:

但我想在条形上方有标签,类似于:

注释掉的代码是我试图使值标签显示在条形上方的尝试。

【问题讨论】:

  • 是".attr("y", (d)-> height - d)" 返回值还是需要将第二个d改为y(d.total)

标签: javascript d3.js


【解决方案1】:

将这段代码粘贴到文本部分应该可以解决问题:

.attr("text-anchor", "middle")
.attr("x", function(d, i) { return i * (width / dataset.length) + (width / dataset.length) / 2; })
.attr("y", function(d) { return height - (d * 10) - 10; })

那里的 -10 与栏有一些距离,在这种情况下显然是 10px。其他数字也需要稍微调整一下,我只是粘贴了我拥有的文件中的代码,所以我不知道它在你的代码上会是什么样子,因为我没有数据集可以尝试。 如果不能,您可以将脚本粘贴到http://jsfiddle.net/,以便我尝试解决吗?告诉我结果如何!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2023-02-23
    • 2021-12-03
    • 1970-01-01
    相关资源
    最近更新 更多