在D3js图表的背景中绘制自定义形状和线段

时间:2019-08-21 13:03:29

标签: angular d3.js charts

我正在使用D3js和Angular制作日志日志图表, 我能够按如下所示绘制比例并绘制数据。

enter image description here

但是现在我的要求是在图表的背景中添加矩形, 例如分段区域,然后需要像以下所示检测绘制的值位于哪个分段。 在logScales上添加矩形的任何帮助以及用于检测哪个段结果绘制点位于

的任何帮助

enter image description here

现在我已经实现了以下代码来绘制LOG LOG Scale和绘制数据,并尝试添加一个矩形 在图表上作为细分。

margin = {top: 10, right: 30, bottom: 30, left: 60};
constructor() { }
ngOnChanges(): void {
 if (!this.data) { return; }
 this.createChart();
}

private createChart() {
d3.select('svg').remove();
const element = this.chartContainer.nativeElement;
const data = this.data;
const svg = d3.select(element)
    .append('svg')
    .attr('width', element.offsetWidth)
    .attr('height', element.offsetHeight)
    .append("g");

const contentWidth = element.offsetWidth - this.margin.left - 
this.margin.right ;
const contentHeight = element.offsetHeight - this.margin.top - 
this.margin.bottom ;

const xAxis = d3
  .scaleLog()
  .domain([0.01, 1000])
  .range([0, contentWidth]);

const yAxis = d3
  .scaleLog()
  .domain([0.001,1000])
  .range([contentHeight,0]);

  const g = svg.append('g').attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')');

  g.append('g')
  .attr('class', 'axis axis--x')
  .attr('transform', 'translate(0,' + contentHeight + ')')
  .call(d3.axisBottom(xAxis).ticks(5,'~g'));

  g.append('g')
  .attr('class', 'axis axis--y')
  .call(d3.axisLeft(yAxis).ticks(5,"~g"))
  .append('text')
  .attr('transform', 'rotate(-90)');

  g.append('g')
  .selectAll("circle")
  .data(data)
  .enter()
  .append("circle")
  .attr("cx", function(d) { return xAxis(d.x)})
  .attr("cy", function(d) { return yAxis(d.y)})
  .attr("r", 4)
  .style("fill", "steelblue");

  // I Tried to put a Rectangle but i am expecting if i can define 
  // its all four coordinates points

  /* g.append('g')
  .append("rect")
  .attr("x",  xAxis(0.01))
  .attr("y",yAxis(0.01))
  .attr("width",xAxis(0.1))
  .attr("height",yAxis(0.01))
  .style("fill","red")
  .style("opacity","0.3");    
 */
 }
 onResize() {
  this.createChart();
}

}

0 个答案:

没有答案