D3 - шаблон обновления v5 для нескольких текстовых элементов - PullRequest
0 голосов
/ 06 января 2020

В следующем коде я попытался создать визуализацию для рынка, на котором каждый покупает в час. Я пытался следовать шаблону обновления v5s, но он не позволил мне соединить два текстовых элемента <text>. Последнее добавленное объединение перезаписывает первое, поэтому 8

Я осмотрелся, но не могу найти ничего, связанного с шаблоном обновления для двух одинаковых элементов.

https://jsfiddle.net/itsahoax/gd2uew73/7/

                const updateCircles = () => {
                    const circles = d3.select('svg')
                        .selectAll('circle');
                    circles
                        .data(dataPoints)
                        .join('circle')
                        .attr('cx', xPosition)
                        .attr('cy', canvasHeight)
                        .attr('r', circleRadius)
                        .attr('id', (d) => d.uniqueid)
                        .attr('fill', (d) => d.color);

                    const text = d3.select('svg')
                        .selectAll('text')
                        .data(dataPoints);

                    text
                        .join()
                        .attr('x', xPosition)
                        .attr('y', canvasHeight)
                        .attr('id', (d) => d.uniqueid)
                        .text((d) => d.description);

                    text
                        .join()
                        .attr('x', xPosition)
                        .attr('y', canvasHeight + 15)
                        .attr('id', (d) => d.uniqueid)
                        .text((d) => `${d.value} KwH`);

                };
                if (update === true) {
                    updateCircles();
                } else {
                    const circles = selection.selectAll('circle')
                        .data(dataPoints, (d) => d.id);

                    const text = selection.selectAll('text')
                        .data(dataPoints);

                    circles
                        .enter().append('circle')
                        .attr('cx', xPosition)
                        .attr('cy', canvasHeight)
                        .attr('r', circleRadius)
                        .attr('id', (d) => d.uniqueid)
                        .attr('fill', (d) => d.color)
                        .merge(circles);

                    text
                        .enter().append('text')
                        .attr('x', xPosition)
                        .attr('y', canvasHeight)
                        .attr('id', (d) => d.uniqueid)
                        .merge(text)
                        .text((d) => d.description);

                    text
                        .enter().append('text')
                        .attr('x', xPosition)
                        .attr('y', canvasHeight + 15)
                        .attr('id', (d) => d.uniqueid)
                        .merge(text)
                        .text((d) => `${d.value} KwH`);
                }
            };

1 Ответ

1 голос
/ 06 января 2020

Не используйте селектор элементов, если у вас есть несколько элементов с различным содержанием с одним и тем же селектором (например, <text>). Добавьте их class и используйте .selectAll('.className') Есть рабочий пример, использующий selection.join JSFiddle .

Подробнее о selection.join здесь .

// render code
        const circles = (selection, dataPoints, isUpdate) => {
            const xPosition = (d, i) => +i * 180 + 100;

            const updateCircles = (data) => {
                const circles = d3.select('svg').selectAll('.circle-area').data(data);

                circles
                  .join((enter) => {
                    enter
                      .append('circle')
                      .attr('class', 'circle-area')
                      .attr('cx', xPosition)
                      .attr('cy', canvasHeight)
                      .attr('r', circleRadius)
                      .attr('id', (d) => d.uniqueid)
                      .attr('fill', (d) => d.color);
                    }, (update) => {
                       update.attr('fill', (d) => d.color);
                    }, (exit) => {
                       exit.remove();
                    });

                const descriptionText = d3.select('svg').selectAll('.kwh-description').data(data);

                descriptionText
                    .join((enter) => {
                      enter
                        .append('text')
                        .attr('class', 'kwh-description')
                        .attr('x', xPosition)
                        .attr('y', canvasHeight)
                        .attr('id', (d) => `description-${d.uniqueid}`)
                        .text((d) => d.description);

                    }, (update) => {
                      update.text((d) => d.description);
                    }, (exit) => {
                      exit.remove();
                    });


                const valueText = d3.select('svg').selectAll('.kwh-value').data(data);

                valueText
                    .join((enter) => {
                      enter
                        .append('text')
                        .attr('class', 'kwh-value')
                        .attr('x', xPosition)
                        .attr('y', canvasHeight + 15)
                        .attr('id', (d) => `value-${d.uniqueid}`)
                        .text((d) => `${d.value} KwH`);

                    }, (update) => {
                      update.text((d) => `${d.value} KwH`);
                    }, (exit) => {
                      exit.remove();
                    });


            };

            if (isUpdate) {
                console.log(dataPoints)
                updateCircles(dataPoints);
            }

        };
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...