Невозможно построить масштаб и оси в точечной диаграмме в Google Data Studio - PullRequest
0 голосов
/ 15 мая 2019

Попытка построить пользовательскую визуализацию рассеянного графика в Google Data Studio.Застрял в создании масштабов и осей. Помогите мне в создании масштабов и осей для графика.

Обратите внимание: - удалили библиотеку d3.min.js, dscc.min.js из файла myViz.jsчтобы сделать его читаемым

Я создал следующие файлы на облачной платформе Google и ссылаюсь на http://bl.ocks.org/weiglemc/6185069 для построения точечного графика.

файлов на облачной платформе Google

manifest.json, myViz.css, myViz.json, myViz.js

https://imgur.com/fJyh71C (Пожалуйста, обратитесь к следующему изображению о том, как выглядит график) Проблема с пользовательской визуализацией в студии данных заключается вя не могу использовать традиционный код d3 в файле, и мне приходится полагаться на чистый ванильный java-скрипт для кодирования.

Мне удалось получить данные (имя хлопья, калории и белки)из следующего файла

https://docs.google.com/spreadsheets/d/1daWp7XM7PJbDLjkXxdVAeVtPem6HJfFEIYRSesQKbpI/edit?usp=sharing

однако я не уверен, как выполнить масштабирование на графике.Приведенный ниже код помогает мне в построении шкалы и осей, но мне понадобится эквивалент кода ванильного javascript.

// setup x 
var xValue = function(d) { return d.Calories;}, // data -> value
    xScale = d3.scale.linear().range([0, width]), // value -> display
    xMap = function(d) { return xScale(xValue(d));}, // data -> display
    xAxis = d3.svg.axis().scale(xScale).orient("bottom");

// setup y
var yValue = function(d) { return d["Protein (g)"];}, // data -> value
    yScale = d3.scale.linear().range([height, 0]), // value -> display
    yMap = function(d) { return yScale(yValue(d));}, // data -> display
    yAxis = d3.svg.axis().scale(yScale).orient("left");

Можете ли вы, ребята, помочь в получении кода.Я вставляю рабочий код, который приводит к точечной диаграмме, как показано на рисунке выше.

manifest.json

{
  "name": "My Visualizations",
  "organization": "MyOrg",
  "description": "My first visualization package.",
  "logoUrl": "https://logo",
  "organizationUrl": "https://url",
  "supportUrl": "https://url",
  "privacyPolicyUrl": "https://url",
  "termsOfServiceUrl": "https://url",
  "packageUrl": "https://url",
  "supportUrl": "https://url",
  "devMode": true,
  "components": [
    {
      "name": "myViz",
      "description": "My first Community Visualization",
      "iconUrl": "https://url",
      "resource": {
        "js": "gs://peekri/myViz.js",
        "config": "gs://peekri/myViz.json",
        "css": "gs://peekri/myViz.css"
      }
    }
  ]
}

myViz.json


         {
              "data": [
                {
                  "id": "concepts",
                  "label": "Concepts",
                  "elements": [
                    {
                      "id": "barDimension",
                      "label": "Dimension",
                      "type": "DIMENSION",
                      "options": {
                        "min": 1,
                        "max": 1
                      }
                    },
                    {
                      "id": "barMetric",
                      "label": "Metric",
                      "type": "METRIC",
                      "options": {
                        "min": 1,
                        "max": 2
                      }
                    }
                  ]
                }
              ],
              "style": [
                {
                  "id": "color",
                  "label": "Colors",
                  "elements": [
                    {
                      "type": "FONT_COLOR",
                      "id": "barColor",
                      "label": "Bar Color",
                      "defaultValue": "black"
                    }
                  ]
                }
              ]
            }

myViz.css

      #myVizTitle {
          color: black;
          font-size: 24px;
          text-align: center;
          margin: 0 auto;
        }

myViz.js

var titleElement = document.createElement('div');
titleElement.id = 'myVizTitle';
document.body.appendChild(titleElement);

function drawViz(data) {
    let rowData = data.tables.DEFAULT;

    // set margins + canvas size
    const margin = {
        top: 10,
        bottom: 50,
        right: 10,
        left: 10
    };
    const padding = {
        top: 15,
        bottom: 15
    };
    const height = dscc.getHeight() - margin.top - margin.bottom;
    const width = dscc.getWidth() - margin.left - margin.right;

    const fillColor = data.style.barColor.value ?
        data.style.barColor.value.color :
        data.style.barColor.defaultValue;

    // remove the svg if it already exists
    if (document.querySelector("svg")) {
        let oldSvg = document.querySelector("svg");
        oldSvg.parentNode.removeChild(oldSvg);
    }

    const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute("height", `${height}px`);
    svg.setAttribute("width", `${width}px`);

    const maxBarHeight = height - padding.top - padding.bottom;
    const barWidth = width / (rowData.length * 2);

    // obtain the maximum bar metric value for scaling purposes
    let xlargestMetric = 0;
    let ylargestMetric = 0;

    rowData.forEach(function(row) {
        xlargestMetric = Math.max(xlargestMetric, row["barMetric"][0]);
    });

    rowData.forEach(function(row) {
        ylargestMetric = Math.max(ylargestMetric, row["barMetric"][1]);
    });

    console.log(xlargestMetric);
    console.log(ylargestMetric);

    rowData.forEach(function(row, i) {
        // 'barDimension' and 'barMetric' come from the id defined in myViz.json
        // 'dimId' is Data Studio's unique field ID, used for the filter interaction
        const barData = {
            dim: row["barDimension"][0],
            met: row["barMetric"][0],
            met2: row["barMetric"][1],
            dimId: data.fields["barDimension"][0].id
        };

        /*// calculates the height of the bar using the row value, maximum bar
        // height, and the maximum metric value calculated earlier
        let barHeight = Math.round((barData["met"] * maxBarHeight) / largestMetric);

        // normalizes the x coordinate of the bar based on the width of the convas
        // and the width of the bar
        let barX = (width / rowData.length) * i + barWidth / 2;*/

        // create the "circle"
        let circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
        circle.setAttribute("r", 3.5);
        circle.setAttribute("cx", barData["met"]);
        circle.setAttribute("cy", barData["met2"]);
        circle.style.fill = fillColor;

        /*rect.setAttribute("x", barX);
        rect.setAttribute("y", maxBarHeight - barHeight);
        rect.setAttribute("width", barWidth);
        rect.setAttribute("height", barHeight);
        rect.setAttribute("data", JSON.stringify(barData));
        // use style selector from Data Studio
        rect.style.fill = fillColor;*/
        svg.appendChild(circle);


        /* // add text labels
         let text = document.createElementNS("http://www.w3.org/2000/svg", "text");
         let textX = barX + barWidth / 2;
         text.setAttribute("x", textX);
         text.setAttribute("text-anchor", "middle");
         let textY = maxBarHeight + padding.top;
         text.setAttribute("y", textY);
         text.setAttribute("fill", fillColor)
         text.innerHTML = barData["dim"];
         svg.appendChild(text);*/
    });

    document.body.appendChild(svg);
}




 dscc.subscribeToData(drawViz, {
        transform: dscc.objectTransform
    });

1 Ответ

0 голосов
/ 25 мая 2019

Проблема с пользовательской визуализацией в студии данных - я не могу использовать традиционный код d3 в файле и полагаться на чистый Ванильный Java-скрипт для кодирования.

Вы действительно можете использовать d3.js с визуализациями сообщества несколькими различными способами:

  1. Вы можете скопировать / вставить или объединить источник d3.js в JavaScript для визуализации. Аналогично шаг 4 кодовой метки, где dscc.min.js и myVizSource.js объединяются вместе, вы также можете объединить d3.min.js в окончательный код JavaScript для визуализации.

  2. Вы можете связать его с вашим источником, используя что-то вроде webpack / npm пример Heatmap здесь.

В качестве альтернативы, если вы хотите построить масштаб / ось без библиотеки визуализации (я бы не рекомендовал это делать).

  1. Создайте функцию масштабирования, которая отображает домен и диапазон вместе.
  2. Добавление строки svg или canvas к html body.
  3. Добавьте отметки и / или ярлыки на тело.
...