为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

江户川乱折腾 2021-06-09 13:01:27
我正在使用 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));
查看完整描述

2 回答

?
森林海

TA贡献2011条经验 获得超2个赞

我像这样绘制我的 y 轴:


  drawYAxis(g: d3.Selection<SVGElement, {}, null, undefined> = this.yAxis) {

    g.selectAll(".label").remove();

    return g.call(

            d3.axisLeft(this.y)

              .ticks(getTickFrequency(this.axes[1].format, this.y.domain()))

              .tickSizeInner(this.x.range()[0] - this.x.range()[1])

              .tickSizeOuter(0)

              .tickFormat(Formatter.short(this.axes[1].format)))

        .call(g => g.select(".tick:last-of-type text")

              .clone()

              .classed("label", true)

              .attr("x", 5 - this.margin.left)

              .text(this.axes[1].label));

  }

所以我像你一样绘制我的 y 轴,使用d3.axisLeft一些额外的选项,然后我用 class选择text附加到最后一个,并复制元素及其样式等。然后我将它向左移动一点,给它是一个不同的类,并将文本设置为预定义的标签。<g>tick


像这样的事情应该有效。请记住,您可以添加不同的类并更改定位以更好地满足您的需求


this.g

    .append("g")

    .call(d3Axis.axisLeft(this.y).ticks(4))

    .select(".tick:last-of-type")

    .append("text")

    .text("My axis label");


查看完整回答
反对 回复 2021-06-24
  • 2 回答
  • 0 关注
  • 192 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信