Подсказка d3 на линейном графике d3 - не может отобразить определенные значения для позиции в строке - PullRequest
0 голосов
/ 18 июня 2019

Я строю линейную диаграмму (используя d3 в приложении Angular 6), и мне хотелось бы отобразить всплывающую подсказку со значениями, соответствующими тому, где на линии находится мышь.

Кажется, я могу получить доступ только к массиву значений, которые строят строку, а не к каждому отдельному значению / индексу. Как я могу это сделать?

Большое спасибо!

Я строю свой совет d3 так:

 const tip = d3Tip()
   tip.attr("class", "d3-tip")
  .style("background-color", '#fff')
  .style("padding", "10px")
  .style("color", "#0c2a47")
  .style("border", "1px solid #c3c3c3")
  .style("border-radius", "4px")

  tip.html(d => {
    return ("<strong>Date:</strong>" + "<br>" + d['display_date'] + "<br>" + "<strong>Depth: </strong>" + d['depth'] + " inches")
  })

И добавьте его в строку следующим образом: ('console.log (d)' будет записывать весь массив значений)

g.append("path")
  .datum(this.tempdata)
  .attr("fill", "none")
  .attr("stroke", "#26aae2")
  .attr("stroke-width", 1.5)
  .attr("d", line)
  .on("mouseover", function (d) {
    tip.show(d, this)
    console.log(d) 
  })
  .on('mouseout', function (d) { tip.hide() });

Вот весь мой код компонента / d3:

import { Component, OnInit, Input, AfterViewInit } from '@angular/core';
import * as d3 from 'd3';
import d3Tip from "../../../../../node_modules/d3-tip"

@Component({
  selector: 'app-depth-site-sum',
  templateUrl: './depth-site-sum.component.html',
  styleUrls: ['./depth-site-sum.component.css']
})
export class DepthSiteSumComponent implements OnInit, AfterViewInit {
  @Input() site_data;
  @Input() send_id;

  constructor() { }

  date: Date;
  dates: any;
  value: Number;
  eachobj: any;
  tempdata: any;
  average: any;
  values: any;
  name: any;
  input_id;

  ngOnInit() {
    this.tempdata = this.site_data
    this.input_id = ""
    this.input_id += "depth_site"
    this.input_id += this.send_id
  }


ngAfterViewInit() {
  var svg = d3.select("#" + this.input_id),
  margin = { top: 20, right: 20, bottom: 30, left: 0 },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom;

var g = svg.append("g")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")")
// .data(this.tempdata .filter(function(v) { return v >= 0 })

var values = this.tempdata.map(function (d) { return d['depth']; });
var sum = 0;
for (var i = 0; i < values.length; i++) {
  if (values[i] != null) {
    sum += parseInt(values[i], 0);
  }
  else { i++ }
}
var baseValue = sum / values.length;

var format = d3.timeFormat("%Y-%m-%d")
var first = this.tempdata[0].dateFL
var last = this.tempdata[(this.tempdata.length) - 1].dateFL


var x = d3.scaleTime()
  .rangeRound([0, width])
  .domain(<[Date, Date]>d3.extent(this.tempdata, function (d) { return d['date']; }));

var y = d3.scaleLinear()
  .rangeRound([height, 0])
  .domain(<[Date, Date]>d3.extent(this.tempdata, function (d) { return d['depth']; }));

var line = d3.line().curve(d3.curveCardinal)
  .x(function (d) { return x(d['date']); })
  .y(function (d) { return y(d['depth']); });

const tip = d3Tip()
tip.attr("class", "d3-tip")
  .style("background-color", '#fff')
  .style("padding", "10px")
  .style("color", "#0c2a47")
  .style("border", "1px solid #c3c3c3")
  .style("border-radius", "4px")
  tip.html(d => {
    return ("<strong>Date:</strong>" + "<br>" + d['display_date'] + "<br>" + "<strong>Depth: </strong>" + d['depth'] + " inches")
  })

svg.call(tip)

// plot first and last dates on x axis
svg.append('g')
  .attr("class", "axis--x")
  .append("text")
  .attr("fill", "#000")
  .attr("x", (width / 2) - 90)
  .attr("y", height + 40)
  .text(first)
  .style("font-size", "09")
  .style('fill', '#5a5a5a');

svg.append('g')
  .attr("class", "axis--x")
  .append("text")
  .attr("fill", "#000")
  .attr("x", (width / 2) + 45)
  .attr("y", height + 40)
  .text(last)
  .style("font-size", "09")
  .style('fill', '#5a5a5a');


g.append("path")
  .datum(this.tempdata)
  .attr("fill", "none")
  .attr("stroke", "#26aae2")
  .attr("stroke-width", 1.5)
  .attr("d", line)
  .on("mouseover", function (d) {
    tip.show(d, this)
    console.log(d)
  })
  .on('mouseout', function (d) { tip.hide() });

d3.selectAll("g").call(tip);
d3.selectAll("g").on('mouseover', tip.show)
  .on('mouseout', tip.hide);

var xAxis = d3.axisBottom(x)

var axisX = svg.append("g")
  .attr("transform", "translate(0," + 70 + ")")
  .attr("fill", "#c3c3c3").attr("opacity", .8)
  .call(d3.axisBottom(x))

axisX.selectAll("text").remove();
  }
}
...