繁体   English   中英

如何在d3柱形图中的y轴上绘制水平线?

[英]how to draw horizontal line in y axis in d3 column chart?

我的angular 6应用程序中有一个d3柱形图,我想在y轴上为y轴上的每个标签绘制线条。 我希望这些行是这样的:

在此处输入图片说明

我不知道该如何画那些浅灰色的线!

这是我来自d3的代码:

createChart() {
const element = this.chartContainer.nativeElement;
this.width = element.offsetWidth - this.margin.left - this.margin.right;
this.height = element.offsetHeight - this.margin.top - this.margin.bottom;
const svg = d3.select(element).append('svg')
  .attr('width', element.offsetWidth)
  .attr('height', element.offsetHeight);

// chart plot area
this.chart = svg.append('g')
  .attr('class', 'bars')
  .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`);

// define X & Y domains
const xDomain = this.data.map(d => d[0]);
const yDomain = [10000, d3.max(this.data, d => d[1])];

// create scales
this.xScale = d3.scaleBand().padding(0.6).domain(xDomain).rangeRound([0, this.width]);
this.yScale = d3.scaleLinear().domain(yDomain).range([this.height, 0]);

// bar colors
this.colors = d3.scaleLinear().domain([0, this.data.length]).range(<any[]>['#00a0e9', '#00a0e9']);

// x & y axis
this.xAxis = svg.append('g')
  .attr('class', 'axis axis-x')
  .attr('transform', `translate(${this.margin.left}, ${this.margin.top + this.height})`)
  .attr("stroke", "#777777")
  .attr("stroke-width", 0.5)
  .attr("fill", "none")
  .call(d3.axisBottom(this.xScale));
this.yAxis = svg.append('g')
  .attr('class', 'axis axis-y')
  .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
  .attr("stroke", "#777777")
  .attr("stroke-width", 0.5)
  .attr("fill", "none")
  .call(d3.axisLeft(this.yScale));
}

** 更新=>

我在y轴下方添加了新配置,效果不错,但是线条的粗细不相等,另一个问题是我有120000和122000的值是两个最大值y,但是图表都为它们绘制了线。 它应该只为120000

this.yAxis = svg.append('g')
  .attr('class', 'axis axis-y')
  .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
  .attr("stroke", "#777777")
  .attr("stroke-width", 0.5)
  .attr("fill", "none")
  .call(d3.axisLeft(this.yScale));

svg.append("g")
  .attr("class", "grid")
  .attr('transform', `translate(${this.margin.left}, ${this.margin.top})`)
  .attr("stroke-width", 0.1)
  .attr("fill", "none")
  .call(d3.axisLeft(this.yScale)
          .tickSize(-this.width)
          .tickFormat("")

  );

在此处输入图片说明

我曾经找到以下代码段:绘制y轴的第二个版本

  g.append("g")
      .attr("class", "grid")
      .call(d3.axisLeft(y)
              .tickSize(-width)
              .tickFormat("")
      );

而且您需要一些CSS来设置线条样式

.grid line {stroke: lightgrey;stroke-opacity: 0.7;shape-rendering: crispEdges;}
.grid path {stroke-width: 0;}

如果只需要网格线而不是轴,则可以使用axis.tickSizeInner([size])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM