javascript - D3 JS条形图,在条形顶部显示y轴标签值

标签 javascript d3.js

我正在使用 Angular 7 和 D3JS V4 来实现条形图,我需要在条形顶部显示 y 轴标签值,我尝试了多种方案但未能做到,请帮我做所以..提前谢谢。

 //Initialize SVG
    this.svg = d3.select("#bar-chart");

    this.width = +this.svg.attr("width") - this.margin.left - this.margin.right;
    this.height =
      +this.svg.attr("height") - this.margin.top - this.margin.bottom;
    this.g = this.svg
      .append("g")
      .attr(
        "transform",
        "translate(" + this.margin.left + "," + this.margin.top + ")"
      );

    //Initialize Axis
    this.x = d3Scale
      .scaleBand()
      .rangeRound([0, this.width])
      .padding(0.9);
    this.y = d3Scale.scaleLinear().rangeRound([this.height, 0]);
    this.x.domain(this.totalStores.map(d => d.store));
    this.y.domain([0, d3Array.max(this.totalStores.map(d => d.storeCount))]);

    //Draw Axis
    this.g
      .append("g")

      .attr("transform", "translate(0," + this.height + ")")
      .call(d3Axis.axisBottom(this.x));
    this.g
      .append("g")

      .call(d3Axis.axisLeft(this.y).ticks(4))
      .append("text");

    //Draw Bars
    this.g
      .selectAll(".bar")
      .data(this.totalStores)
      .enter()
      .append("rect")
      .attr("class", "bar")
      .attr("x", d => this.x(d.store))
      .attr("y", d => this.y(d.storeCount))
      .attr("width", this.x.bandwidth())
      .attr("height", d => this.height - this.y(d.storeCount));


jsFiddle

最佳答案

只需将 x 和 y 值传递给文本即可

// Get the y axis value on top
this.g
        .selectAll("text.bar")
        .data(this.totalStores)
        .enter()
        .append("text")
        .attr("class", "yAxis-label")
        .attr("text-anchor", "middle")
        .attr("fill", "#70747a")
        .attr("x", d => this.x(d.store))
        .attr("y", d => this.y(d.storeCount) - 5)
        .text(d => d.storeCount);

关于javascript - D3 JS条形图,在条形顶部显示y轴标签值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56521904/

相关文章:

javascript - D3 v4 网格 : How do I bind the data properly?

javascript - 如何在 javascript 中以正确的方式编写此代码

javascript - 保持一个按钮处于事件状态

javascript - 如何在没有javascript的情况下检测浏览器并显示消息?

git - 如何在给定缩小文件的情况下找到 D3 的确切版本?

javascript - 如何使用 d3.js 将层次图的曲线变为直线

javascript - Mouseevent div 覆盖图表上的 div

javascript - 如何使用 JavaScript 从选项 DOM 元素中获取先前和新的选定值?

javascript - 验证 focusout 和 click 事件

javascript - 定义时的 D3 样式 SVG 元素