Google Charts TreeMap 노드 서식 지정

빨간

내 데이터에 대한 멋진 트리 맵이 생성되었으며 모두 작동하며 이름에 값을 추가 할 수 있었지만 훨씬 더 나을 수 있습니다.

Google Analytics에서 사용할 수있는 트리 맵에는 값과 하위 값을 포함하여 매우 다른 형식의 노드가 있습니다. 우리가 사용할 수있는 차트를 사용하여 이와 같이 각 노드에 대해 렌더링되는 html 블록을 형식화하는 방법이 있습니까?

여기에 이미지 설명 입력

흰색 모자


레이블의 텍스트 스타일을 변경하는 것 외에는 표준 구성 옵션으로 할 수있는 일이 많지 않습니다.

그러나 이벤트가 발생
하면 기존 요소를 수동으로 변경하거나 차트에 고유 한 요소를 추가 할 수 있습니다 'ready'.

그러나 원래 레이블을 이동 / 변경하려면
원래 스타일 / 마우스 오버시 위치로 돌아가거나 다른 활동에서
a MutationObserver사용 하여 재정의해야합니다.

라벨을 추가하는 예는 다음 작업 스 니펫을 참조하세요.

각 위치의 자식 수가 정적 레이블-> 'Children'
함께 추가 되고 레이블은 제공된 그림과 같이 왼쪽 상단 모서리로 이동합니다.

google.charts.load('current', {
  packages: ['treemap']
}).then(function () {
  var data = google.visualization.arrayToDataTable([
    ['Location', 'Parent', 'Market trade volume (size)', 'Market increase/decrease (color)'],
    ['Global', null, 0, 0],
    ['America', 'Global', 0, 0],
    ['Europe', 'Global', 30, 0],
    ['Asia', 'Global', 10, 0],
    ['Australia', 'Global', 40, 0],
    ['Africa', 'Global', 30, 0],
    [{ v: 'USA', f: 'United States of America' }, 'America', 20, 0],
    ['Mexico', 'America', 24, 12],
    ['Canada', 'America', 16, -23],
    ['Ontario', 'Canada', 12, -9],
    ['Alberta', 'Canada', 24, 13],
    ['UK', 'Europe', 21, -5],
    [{ v: '123', f: 'London' }, 'UK', 21, -5],
    [{ v: '456', f: 'London' }, 'Ontario', 21, -5],
    ['Ohio', 'USA', 12, 3],
    ['Rhode Island', 'USA', 24, 4]
  ]);

  var container = document.getElementById('chart_div');
  var tree = new google.visualization.TreeMap(container);
  var newLabelCoords = {x: 8, y: 16};

  google.visualization.events.addListener(tree, 'ready', addChildLabels);
  google.visualization.events.addListener(tree, 'select', addChildLabels);

  var observer = new MutationObserver(moveOriginalLabels);
  observer.observe(container, {
    childList: true,
    subtree: true
  });

  // find / move original labels
  function moveOriginalLabels() {
    Array.prototype.forEach.call(container.getElementsByTagName('text'), function(text) {
      var bounds = text.getBBox();
      var rect = text.parentNode.getElementsByTagName('rect')[0];
      if ((rect.getAttribute('fill') !== '#cccccc') && (text.getAttribute('text-anchor') === 'middle')) {
        text.setAttribute('fill', '#424242');
        text.setAttribute('font-weight', 'bold');
        text.setAttribute('x', parseFloat(rect.getAttribute('x')) + newLabelCoords.x + (bounds.width / 2));
        text.setAttribute('y', parseFloat(rect.getAttribute('y')) + newLabelCoords.y);
      }
    });
  }

  function addChildLabels() {
    // hold new labels
    var childCount = [];
    var childLabels = [];

    // svg namespace
    var svgNS = container.getElementsByTagName('svg')[0].namespaceURI;

    // find existing / build new labels
    Array.prototype.forEach.call(container.getElementsByTagName('text'), function(text) {
      if (text.getAttribute('text-anchor') === 'middle') {
        var rect = text.parentNode.getElementsByTagName('rect')[0];

        // exclude top node
        if (rect.getAttribute('fill') !== '#cccccc') {
          moveOriginalLabels();

          // find node value
          var nodeValue;
          for (var i = 0; i < data.getNumberOfRows(); i++) {
            if ((data.getValue(i, 0) === text.textContent) ||
                (data.getFormattedValue(i, 0) === text.textContent)) {
              nodeValue = data.getValue(i, 0);
            }
          }

          // find # of children
          var children = data.getFilteredRows([{
            column: 1,
            value: nodeValue
          }]);

          // add child count
          var textCount = document.createElementNS(svgNS, 'text');
          textCount.setAttribute('fill', '#000000');
          textCount.setAttribute('font-family', 'Arial');
          textCount.setAttribute('font-size', '24');
          textCount.setAttribute('font-weight', 'bold');
          textCount.setAttribute('x', parseFloat(rect.getAttribute('x')) + newLabelCoords.x);
          textCount.setAttribute('y', parseFloat(text.getAttribute('y')) + parseFloat(textCount.getAttribute('font-size')));
          textCount.textContent = children.length;
          childCount.push([text, textCount]);

          // add 'Children' label
          var textLabel = document.createElementNS(svgNS, 'text');
          textLabel.setAttribute('fill', '#000000');
          textLabel.setAttribute('font-family', 'Arial');
          textLabel.setAttribute('font-size', text.getAttribute('font-size'));
          textLabel.setAttribute('font-weight', 'bold');
          textLabel.setAttribute('x', parseFloat(rect.getAttribute('x')) + newLabelCoords.x);
          textLabel.setAttribute('y', parseFloat(textCount.getAttribute('y')) + parseFloat(textLabel.getAttribute('font-size')) + 2);
          textLabel.textContent = 'Children';
          childLabels.push([text, textLabel]);
        }
      }
    });

    // append new labels
    childCount.forEach(function (text) {
      text[0].parentNode.appendChild(text[1]);
    });
    childLabels.forEach(function (text) {
      text[0].parentNode.appendChild(text[1]);
    });
  }

  drawTree();
  window.addEventListener('resize', drawTree);
  function drawTree() {
    tree.draw(data, {
      minColor: '#f00',
      midColor: '#ddd',
      maxColor: '#0d0',
      headerHeight: 15,
      fontColor: 'black'
    });
  }
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

SpriteKit에서 개체의 자식 노드에 대한 터치 감지

Google Charts: Legendenposition verschieben

노드에서 특정 노드 선택

Google Charts - сумма отображаемых столбцов со слайдером

C # LINQ에서 자식 노드 XML에 따라 특정 부모 노드 가져 오기

Google charts with two series on charts (SQL/PHP)

Google Charts interpolateNulls not working

Google Charts interpolateNulls no funciona

Google Charts: Data in the axis

Google charts vAxis

Google Charts API Change Font

C # XML 문서 클래스를 사용하여 자식 노드 값 수정

노드 js 함수 onWrite가 Google 클라우드 기능에서 제대로 작동하지 않습니다.

Chart is not displaying (google charts + codeigniter)

양식 제출에서 노드 연결 플래시가 작동하지 않음

Google Charts: как установить максимальное значение столбца без большого промежутка между ними. (Столбцы)

TreeMap получает первый элемент и удаляет

Написание собственного класса TreeMap - что расширить и / или реализовать?

Google Charts, как исправить дефис, преобразованный в & # 8211;

Использование моего собственного объекта в качестве ключа в TreeMap

отправить параметры Google Charts с помощью обратного вызова

Формат чисел в подсказке Google Chart Treemap Tooltip

Временная шкала из Google Charts не распознает цвета

Отправляет ли GraphDB Google Charts мои данные куда-нибудь, кроме моего собственного сервера или клиента?

Я спрашиваю о Google Charts

Форматирование данных для Google Charts

Как вы кодируете общую сумму на каждой столбчатой диаграмме с накоплением (Google Charts)?

Лучший способ отсортировать TreeMap по значениям

Ограничен ли google charts stringFilter 29 символами?

TOP Lista

  1. 1

    ¿Cómo ocultar la aplicación web de los robots de búsqueda? (ASP.NET)

  2. 2

    Kibana 4 , making pie chart , error message

  3. 3

    Manera correcta de agregar referencias al proyecto C # de modo que sean compatibles con el control de versiones

  4. 4

    récupérer les noms de clés depuis Firebase react-native

  5. 5

    OAuth 2.0 utilizando Spring Security + WSO2 Identity Server

  6. 6

    Cómo eliminar o caducar las cookies en Chrome usando asp.net

  7. 7

    desbordamiento: oculto no funciona al hacer zoom en un iframe de YouTube usando transformar

  8. 8

    Cómo extraer una palabra clave (cadena) de una columna en pandas dataframe en python

  9. 9

    Link library in Visual Studio, why two different ways?

  10. 10

    선언되지 않은 유형 'MessagingDelegate'사용

  11. 11

    actualizar el contenido de la vista de reciclaje falla en la hoja inferior

  12. 12

    Ver todos los comentarios en un video de YouTube

  13. 13

    Problema con la vista de impresión de PDF

  14. 14

    ¿Cómo pintar el Dropline de un RowHeader-JTable en el Main-JTable durante un DragAndDrop?

  15. 15

    Pregunta de fórmula de desplazamiento y transposición de Excel / Google Sheets

  16. 16

    ¿Cómo puedo hacer accesible la información de color en tablas HTML?

  17. 17

    ¿Cómo generalizar el JSON en el procedimiento almacenado?

  18. 18

    Recortar fotos rectangulares de escaneos en OpenCV con Python

  19. 19

    2D 배열에 대한 Numpy 요소 별 평균 계산

  20. 20

    Typescript의 "window"전역 개체에 "adsbygoogle"애드 센스 속성을 추가하는 방법은 무엇입니까?

  21. 21

    Error: la ejecución falló para la tarea ': app: compileDebugJavaWithJavac'. java.io.FileNotFoundException:

CalienteEtiquetas

Archivo