График d3. js без учета полей - PullRequest
0 голосов
/ 23 марта 2020

Итак, я определяю поля здесь:

  const svg1 = d3.select(graphElement1.current);
  const margin = {top: 0, right: 30, bottom: 10, left: 10};
  const width = 650 - margin.left - margin.right;
  const height = 100 - margin.top - margin.bottom;

Рисуем график здесь

    const data = timeseries;

    const x = d3.scaleTime()
        .domain(d3.extent(data, function(d) {
          return new Date(d['date']+'2020');
        }))
        .range([0, width]);

    const y = d3.scaleLinear()
        .domain([0, d3.max(data, function(d) {
          return +d['totalconfirmed'];
        })])
        .range([height, 0]);

    svg1.append('g')
        .attr('transform', 'translate(0,' + height + ')')
        .attr('class', 'axis')
        .call(d3.axisBottom(x));

svg1.append('path')
        .datum(data)
        .attr('fill', 'none')
        .attr('stroke', '#ff073a99')
        .attr('stroke-width', 5)
        .attr('cursor', 'pointer')
        .attr('d', d3.line()
            .x(function(d) {
              return x(new Date(d['date']+'2020'));
            })
            .y(function(d) {
              return y(d['totalconfirmed'])-5;
            })
            .curve(d3.curveCardinal),
        );

    svg1.selectAll('.dot')
        .data(data)
        .enter()
        .append('circle')
        .attr('fill', '#ff073a')
        .attr('stroke', '#ff073a')
        .attr('r', 3)
        .attr('cursor', 'pointer')
        .attr('cx', function(d) {
          return x(new Date(d['date']+'2020'));
        })
        .attr('cy', function(d) {
          return y(d['totalconfirmed'])-5;
        })
        .on('mouseover', (d, i) => {
          d3.select(d3.event.target).attr('r', '5');
          setDatapoint(d);
          setIndex(i);
        })
        .on('mouseout', (d) => {
          d3.select(d3.event.target).attr('r', '3');
        });

И это структура div диаграммы:

        <div className="svg-parent">
          <div className="stats">
            <h5>Confirmed {datapoint['date']}</h5>
            <div className="stats-bottom">
               ...
            </div>
          </div>
          <svg ref={graphElement1} width="650" height="100" viewBox="0 0 650 100" preserveAspectRatio="xMidYMid meet"/>
        </div>

И это CSS:

  .svg-parent {
    display: flex;
    flex: 0.9;
    flex-direction: row;
    justify-content: center;
    width: 100%;
    svg {
      align-self: center;
    }
  }

Я пробовал много CSS правил, чтобы svg уважал определение поля, но я не могу заставить его работать , Я не могу показать ось X также в результате.

Вот так это выглядит сейчас, работает правое поле, однако,

image

[Отредактировано; даже после установки значения влево график не сдвигается вправо]

1 Ответ

2 голосов
/ 23 марта 2020

Как объяснено в этого урока :

Эти поля будут использоваться для вставки диапазонов наших весов. Вместо расширения от 0 до полной ширины и высоты диаграммы начало и конец диапазонов перемещаются внутрь на соответствующие поля.

Так что для шкалы оси x замените .range([0, width]) от:

.range([margin.left, width])

И, аналогично, для оси y попробуйте следующее для определения диапазона:

.range([height, margin.top])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...