简体   繁体   中英

Unable to plot scales and axes in scatter plot in google data studio

Trying to build scatter plot custom visualization in google data studio. Stuck with creating scales and axes.Help me in creating the scales and axes to the plot.

Please note:- have removed the d3.min.js, dscc.min.js library from the myViz.js file to make it readable

I have created the below files in google cloud platform and have been referring to http://bl.ocks.org/weiglemc/6185069 for building the scatter plot.

files on the google cloud platform

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

https://imgur.com/fJyh71C (Please refer to the following image on how the graph looks) The problem with data studio custom visualization is i am not able to use the tradition d3 code in the file and have to rely on the pure vanilla java script to do the coding.

I have been able to pull the data(Cereal Name, calaories and proteins) from the following file

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

however m not sure how to do the scaling on the chart. The below code helps me in ploting the scale and axes but i will need the vanilla javascript equivalent of the code.

// 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");

can you guys help in getting the code. iam pasting the working code which reulted in scatter plot as shown in the pic above.

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
    });

The problem with data studio custom visualization is i am not able to use the tradition d3 code in the file and have to rely on the pure vanilla java script to do the coding.

You can actually use d3.js with community visualizations a few different ways:

  1. You can copy/paste or concatenate the d3.js source into your visualization JavaScript. Similarly to step 4 of the codelab, where dscc.min.js and myVizSource.js are being concatenated together, you can also concatenate d3.min.js into your final visualization JavaScript.

  2. You can bundle it into your source using something like webpack/npm heatmap example here.

Alternatively, if you wanted to construct a scale/axis without a visualization library (I wouldn't recommend it).

  1. Create a scaling function that maps a domain and range together.
  2. Append an svg or canvas line to the html body.
  3. Add tick marks and/or labels to the body.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM