How can I utilize JSON data to retrieve information using D3 library?

Currently, I am experimenting with learning D3 JS and endeavoring to create a bar chart using real-time data fetched from the openweather API. My aim is to display the City Name along with its corresponding temperature at the time of the query.

However, as I proceed with setting up my chart, I face the recurrent issue of receiving NaN (Not a Number) for each bars' height and width values. To provide some context, I have a function that loops through the data, generating an object containing the city's temperature and name. These objects are then stored in an array called 'weather', which serves as the data source for my chart.

I would greatly appreciate it if someone could shed light on why I'm encountering NaN errors and offer insights into how I can specifically retrieve the temperature values from the data.

var weather =[];
var name;

var margin = {
top: 50,
right:30,
bottom:40,
left:50
}

var height = 500 - margin.top - margin.bottom ,
width = 600 - margin.left - margin.right,
barwidth = 50,
barOffset = 5;

var yScale = d3.scale.linear()
    .domain([0, d3.max(weather)])
    .range([0, height]);

var xScale = d3.scale.ordinal()
    .domain(d3.range(0, weather.length))
    .rangeBands([0, width], .2)

var tempColor;

//Load external data//
d3.json("http://api.openweathermap.org/data/2.5/group?id=192710,2643743,1850147,2988507,524901,5368361,1816670,2177052,1835847,3128760,7533612,292223,7870410,3451190,1275339,4904381,5856195,&units=metric", function(data){

var list = data.list

for (var i = 0; i<list.length; i++){
    var country = list[i]
    var nameOfCountry = list[i].name
    var temperature = +country.main.temp
    var countryWeather = [ nameOfCountry, temperature ]

    weather.push({ "temperature":temperature, "nameOfCountry":nameOfCountry})
}
console.log(weather)

// Horizontal Color Gradient for bars
var colors = d3.scale.linear()
    .domain([0, weather.length*.33, weather.length*.66, weather.length])
    .range(['#FFB832','#C61C6F','#268BD2','#85992C'])


//Create the canvas//
var Canvas = d3.select('#chart').append('svg')
.style('background','#FFF')
.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
    .append('g')
    .attr('transform','translate(' + margin.left + ',' + margin.top + ')')
    .style('background', '#C9D7D6')
        .selectAll('rect').data(weather)
        .enter().append('rect')
            .style('fill', function(d,i){
                return colors(i);
            })
        .attr('width', xScale.rangeBand())
            .attr('height', 0)
            .attr('x',function(d,i){
                return xScale(i);
            })
            .attr('y', height)
            .on('mouseover', function(d){

                tooltip.transition()
                    .style('opacity', .9)

                tooltip.html(d)
                    .style('left',(d3.event.pageX - 35) + 'px')
                    .style('top', (d3.event.pageY - 35) + 'px')

                tempColor = this.style.fill;
                d3.select(this)
                    .transition().delay(500).duration(800)
                    .style('opacity', .5)
                    .style('fill', 'yellow')
            })
            .on('mouseout',function(d){
                d3.select(this)
                    .transition().delay(500).duration(800)
                    .style('opacity',1)
                    .style('fill', tempColor)
            })

Canvas.transition()
.attr('height',function(d){
    return yScale(d);
})
.attr('y', function(d){
    return height - yScale(d);
})
.delay(function(d,i){
    return i * 20;
})
.duration(800)
.ease('elastic')

var vGuideScale = d3.scale.linear()
.domain([0,d3.max(weather)])
.range([height,0])

var vAxis = d3.svg.axis()
.scale(vGuideScale)
.orient('left')
.ticks(10)

var vGuide = d3.select('svg').append('g')
vAxis(vGuide)
vGuide.attr('transform','translate(' + margin.left + ',' + margin.top +')')
vGuide.selectAll('path')
    .style({
        fill:'none',
        stroke: '#000'
    })
vGuide.selectAll('line')
    .style({
        stroke: '#000'
    })

var hAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom')
.tickValues(xScale.domain().filter(function(d,i){
    return !(i % (weather.length/5)) 
}))

var hGuide = d3.select('svg').append('g')
hAxis(hGuide)
hGuide.attr('transform','translate(' + (margin.left-6) + ',' + (height + margin.top) +')')
hGuide.selectAll('path')
    .style({
        fill:'none',
        stroke: "#000"
    })
hGuide.selectAll('line')
    .style({
        stroke:"#000"
    })
});

Answer №1

It seems that the domain for your website is not correctly configured

var yScale = d3.scale.linear()
    //.domain([0, d3.max(weather)]) Remove this line
    .range([0, height]);

You should remove the mentioned line and add it after the weather data has been filled. Utilize the d3.extent() function to retrieve both the minimum and maximum values of weather.temperature concurrently

for (var i = 0; i<list.length; i++){
    var country = list[i]
    var nameOfCountry = list[i].name
    var temperature = +country.main.temp
    var countryWeather = [ nameOfCountry, temperature ]

    weather.push({ "temperature":temperature, "nameOfCountry":nameOfCountry})
}
yScale.domain(d3.extent(weather, function(d) { return d.temperature; }));
console.log(weather)

Additionally, remember to specifically access the temperature attribute

Canvas.transition()
.attr('height',function(d){
    return yScale(d.temperature);
})
.attr('y', function(d){
    return height - yScale(d.temperature);
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a surprise Illegal Token JS Error

I am encountering a persistent "Unexpected Token ILLEGAL" error while attempting to run the script on the page after it has been registered. StringBuilder str = new StringBuilder(); str.Append("<script type='text/javascript&apos ...

Exploring the application of Nested Maps in extracting parameters for the getStaticPaths

Your data structure is organized like this: data = { "cse": { "first": [ "Computer Hardware Essentials", "Computer System Essentials", "Cultural Education" ], "second&qu ...

What are the methods to ascertain whether an HTML element possesses a pseudo element?

Is there a method to identify whether an HTML element has a pseudo element (::before / ::after) applied to it without invoking the function: window.getComputedStyle(element, ":before/:after"); MODIFIED: the response is NEGATIVE The issue with getCompute ...

Unable to retrieve information from the JSON object

Here's the script I'm working with: <script type="text/javascript> function getData(username){ $.ajax({ url: '{% url "data" %}', data: { ' ...

Unable to interpret data from the API

{ id: 8, customerName: "xyz", customerMobileNumber: "123456789", customerBillingAddress: "xyz address", customerShippingAddress: "xyz address", customerProductPurchasedDate: "2021-11-09T09:07:00.000Z", cust ...

Sending a series of filtered GET requests to my Express backend in a MERN (MongoDB, Express, React,

I have developed a MERN web application and am in the process of adding some GET methods to retrieve the same item for different scenarios. However, when I attempt to implement a second filter method and pass an existing parameter in my item schema, Postma ...

Retrieving a property of an object within an array using JavaScript in AngularJS

Seeking advice on how to calculate the total price of products in an array when working within a callback function. Is there a method similar to myArray.(intheobject).price? Or is there a way to handle callbacks effectively to achieve accurate results? th ...

You cannot assign an optional parameter in Express after it has already been declared

Having trouble with passing optional parameters in my param function as defined below. During testing in Postman, I keep encountering a Reference Error 'off' is not defined. It seems like I'm missing something crucial in how to utilize the p ...

Ways to access the value of an input field using Javascript

I am currently utilizing the valums-file-uploader plugin for file uploads via ajax. However, I have encountered an issue with its functionality. Below is the script that I am using: <input type="text" id="Gaurav" name="Gaurav" /> <script src="fil ...

Unable to update JSON response in Firefox browser

Within my MVC view, I have an HTML SPAN with the class "displayText" that contains attributes for "typeId" and "idValue". The goal is to retrieve the DisplayText property from a database table based on the provided "typeId" and "idValue". Since there are ...

Creating specifications for query parameters in Loopback that are essential for handling CRUD operations

Our journey with Loopback has been successful thus far, but we are now looking to enhance our API documentation by including query parameters. In the swagger.json file, there could be a section that resembles this: { "swagger": "2.0", "i ...

Setting the default value of a multi-select dropdown in AngularJS from the controller

Currently, I have implemented AngularJS multi select drop down functionality on my website. The code for this can be found at the following source: MultiSelectDropDown In my HTML page, I have included the same drop down twice and I want to customize the ...

I am unable to sketch my backdrop. - HTML Canvas Game

Recently I've encountered an issue in my code where the image doesn't appear and mouse interaction stops working when I uncomment bg.draw() within the draw function. function draw() { clearAllCtx(); player.draw(); ene ...

How can you create an accordion menu that expands when a button is clicked?

Is there a way to make an accordion menu open when the 'More' button is clicked? I've tried, but it always starts in its expanded state and collapses when the button is clicked. What I really want is for the accordion to be closed initially ...

Dealing with JSON object as a string in API using Laravel with PHP

I have a Python API that generates a JSON object with data on staff behavior. The response looks like this: { "Text":{ "0":"Very unfriendly staff at reception: not responding to needs and giving wrong information.", "1":"The staff are polit ...

Introducing the innovative Icon Collapsable JQuery - a versatile tool that

I'm looking to set custom icons for the JQuery Collapsable view without having to make changes to the default JQuery CSS and .JS files. You can take a look at my starting point on jsFiddle here: http://jsfiddle.net/jakechasan/M7LLU/ Although I' ...

Jquery display function experiencing unresponsiveness

Currently, I am trying to implement some show/hide functionality in my JavaScript file: $(document).ready(function() { $('#me').hide(); $('#send').click(function() { $('#me').show("slow"); }); }); Strange ...

Node JS Axios Network Error due to CORS Policy Restrictions

When attempting to make a put axios request, I encounter the following error: https://i.sstatic.net/aBQGI.png I have installed and enabled the CORS module in the server.js file, but it doesn't seem to be working. Additionally, there are no CORS head ...

Why is the jQuery change event only firing when the page loads?

I am experiencing an issue with a .js file. The change event is only triggering when the page loads, rather than when the selection changes as expected. $(document).ready(function(){ $("#dropdown").on("change keyup", colorizeSelect()).change(); }); f ...

Retrieve the targeted row from the table and then employ a function

Here is a datatable that I am working on: http://jsbin.com/OJAnaji/15/edit I initially populate the table with data and display it. Then, I add a new column called "kontrole." data = google.visualization.arrayToDataTable([ ['Name', &apo ...