Data Visualization Projects - Visualize Data with a Heat Map

Tell us what’s happening:

Dataset is undefined after assigning json data in req.onload()

dataset and baseTemp are variables declared at the beginning of my program. Although they are undefined when declared, when the api request loads, they are assigned values json.monthlyVariance and json.baseTemperature respectively. However, from my console, it shows that dataset and baseTemp remain undefined even after the value assignment. This affects the entire functionality of my program.

Your code so far

> import * as d3 from "https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js";
> 
> const heatMap = document.getElementById('heat-map');
> 
> let dataset = [];
> let baseTemp = "";
> 
> const req = new XMLHttpRequest();
> 
> req.open("GET", 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json', true);
> req.send();
> 
> req.onload = () => {
>     const json = JSON.parse(req.responseText);
>     dataset = json.monthlyVariance;
>     baseTemp = parseFloat(json.baseTemperature);
>     console.log('DATASET:\n', dataset, "\nBase Temperature:\n", baseTemp);
> 
>     plotMap();
> }
> 
> function plotMap() {
> 
>     const padding = 40;
>     const width = (1.8 * heatMap.clientWidth);
>     const height = heatMap.clientWidth;
> 
>     const minYear = d3.min(dataset, d => d.year);
>     const maxYear = d3.max(dataset, d => d.year);
> 
>     const minMonth = d3.min(dataset, d => d.month);
>     const maxMonth = d3.max(dataset, d => d.month);
> 
>     const cellWidth = (width - (2 * padding)) / (maxYear - minYear + 1);
>     const cellHeight = (height - padding) / (maxMonth - minMonth + 1);
> 
>     //x-dcale for years
>     const xScale = d3.scaleLinear()
>                      .domain([minYear, maxYear])
>                      .range([padding, width - padding]);
> 
>     // y-scale for months
>     const yScale = d3.scaleBand()
>                      .domain(d3.range(12))
>                      .range([padding, height - padding]);
> 
>     // color scale for temperature
>     const colorScale = d3.scaleSequential(d3.interpolateRdYlBu.reverse())
>                          .domain(d3.extent(dataset, d => baseTemp + d.variance));
> 
>     const svgMap = d3.select(heatMap)
>                      .append('svg')
>                      .attr('width', width)
>                      .attr('height', height)
>                      .attr('id', 'svg-map');
> 
>     svgMap.selectAll('rect')
>           .data(dataset)
>           .enter()
>           .append('rect')
>           .attr('class', 'cell')
>           .attr('width', cellWidth)
>           .attr('height', cellHeight)
>           .attr('x', d => xScale(d.year))
>           .attr('y', d => yScale(d.month - 1))
>           .attr('data-month', d => d.month)
>           .attr('data-year', d => d.year)
>           .attr('data-temp', d => (d.variance + baseTemp).toFixed(2))
>           .attr('fill', d => colorScale(baseTemp + d.variance));
> 
> 
> }

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36

Challenge Information:

Data Visualization Projects - Visualize Data with a Heat Map

How did you run this, what console are you referring to and what IDE? Did you try to use Code pen or your own like VScode.

I deployed on netlify.com, and used the Console on the developer tools on Google Chrome

I’ve edited your code for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

1 Like

You might have a problem where the code is being run before the data is fetched.

I found this d3.json().then() structure to work well to make sure the data is loaded and then your code is run.

https://stackoverflow.com/questions/22325819/d3-js-get-json-from-url

d3.json("http://127.0.0.1:8080/mydata.json").then( data => {
    console.log(data);
})
d3.json(url)
  .then((response) => {
        //console.log(response);
        functionwithyourcode(response);
                    });