Issue with rendering D3 horizon chart is not displaying

I am attempting to create a horizon chart using D3.js and Horizon.js, inspired by this example from Jason Davies. I am working with fitness tracker data.

However, the example by Mike Bostock uses a unique JSON structure and performs some complicated row-to-column transformations, making it difficult to follow.

In my JSFiddle demo, nothing is rendered - not even an error message. My code and data resemble the following:

var data=[{"key":"active time","date":"05/13/2013","value":"3860.0"},{"key":"active time","date":"05/14/2013","value":"5167.0"},
{"key":"active time","date":"05/15/2013","value":"5663.0"},
{"key":"active time","date":"05/22/2013","value":"3371.0"},{"key":"distance","date":"05/13/2013","value":"5766.0"},{"key":"distance","date":"05/14/2013","value":"7472.0"},{"key":"distance","date":"05/15/2013","value":"8264.0"},{"key":"distance","date":"05/22/2013","value":"4989.0"},{"key":"steps","date":"05/13/2013","value":"7210.0"},{"key":"steps","date":"05/14/2013","value":"9481.0"},{"key":"steps","date":"05/15/2013","value":"10431.0"},{"key":"steps","date":"05/16/2013","value":"1006.0"},{"key":"steps","date":"05/22/2013","value":"6268.0"}];

    data.forEach(function(d) {
        var parseDate = d3.time.format("%m/%d/%Y").parse;
        d.date = parseDate(d.date); 
        d.value = Math.round(+d.value);
        });

var margin  = {top:5, right:5, bottom:5, left:5},
    height  = 500 - margin.top - margin.bottom, 
    width   = 500 - margin.left - margin.right;

var chart = d3.horizon()
    .width(width)
    .height(height)
    .bands(1)
    .mode("mirror")
    .interpolate("basis");

var svg = d3.select("#body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.data([data]).call(chart);

I need assistance in understanding how to format my JSON data correctly for this visualization. Is this the issue at hand?

Thank you

Answer №1

It appears that your SVG is not appearing on the page due to the absence of an element with id="body". To rectify this, line 218 should utilize the tag selector body instead of the id selector #body, allowing the SVG to be properly included in the document.

The data points within the SVG are currently displaying as NaN, indicating a potential issue with the data format being utilized. It is recommended to compare your data structure with the example data provided:

The example data seems to consist of a two-dimensional array in the format [timestamp, value] arranged by timestamp.

Referencing the data manipulation method from http://bl.ocks.org/mbostock/1483226#index.html:

data = data.rate.map(function(rate, i) {
    return [Date.UTC(data.year[i], data.month[i] - 1), rate - mean];
});

If you structure your data similarly, it should resolve the issue. Consider implementing the following approach:

console.log('before: ', data);
data = data.map(function(obj, i) {
    return [obj.date.getTime(), obj.value];
}).sort(function(a, b) { 
    return a[0] > b[0] ? 1 : (a[0] == b[0] ? 0 : -1); 
});
console.log('after: ', data);
svg.data([data]).call(chart);

Following these steps should result in the desired visualization. It is advisable to review the data transformation process to ensure accuracy in translation.

NOTE: The code snippet provided consolidates the three data key segments (active time, distance, and steps) into a single array. You may need to separate these into distinct series as required.

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

Modify CSS class if user is using Internet Explorer version 10 or above

I am attempting to modify the CSS of 2 ASP controls using jQuery specifically for users accessing the site with Internet Explorer 10 or 11. This adjustment is necessary because IE10 onwards, conditional comments are no longer supported. My approach to achi ...

What is the best way to eliminate the nesting in this ternary operation?

Object.values(filter).filter(item => (Array.isArray(item) && item.length > 0) || (typeof item === "boolean" && item === true) || (item !== null)).length ? filterIcon : unFilledIcon In this code, I aim to simplify the nested ternary operator and ...

Setting up Spectron

I attempted to install Spectron using the following command: npm install --save-dev spectron However, I encountered the following error message: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\Program Files\nodejs\node.exe" "C:\P ...

Getting the Tweets of a Twitter-validated user using node.js

I'm struggling with extracting Tweets from a verified user and could use some assistance. I know it's a broad question, but here's the situation: https://github.com/ttezel/twit provides a way to access tweets from any Twitter account. Howev ...

Looking to merge two components into one single form using Angular?

I am currently developing an Angular application with a dynamic form feature. The data for the dynamic form is loaded through JSON, which is divided into two parts: part 1 and part 2. // JSON Data Part 1 jsonDataPart1: any = [ { "e ...

Trouble accessing environment variables within a React application, specifically when using webpack's DefinePlugin in a Dockerfile

I can't figure out why console.log is printing undefined. The files Makefile, config.env, webpack.config.js, and package.json are all located in the root of my project. Makefile: docker-run: docker docker run -it --env-file config.env -p "80:80" ...

Disable reloading when submitting and reset input fields after submission

I am working on developing a website where users can post things and comments without the need to refresh the page. I have encountered some issues while implementing this feature and need some assistance with it. My goal is to allow users to submit comment ...

What is the best approach in AngularJS for implementing a browser modal that returns a promise?

How can I implement a custom modal in my code that allows me to perform an action only after the user clicks 'okay'? var modalInstance = this.$modal.open({ templateUrl: '/app/tests/partials/markTest.html', controller: ['$sc ...

Props does not solely rely on Vue.js for data feeding

My journey with learning vue has just started, and I recently incorporated a prop into my vue component. At first glance, the code appeared to be correct, but then something unexpected occurred. import Vue from 'vue'; import App from './A ...

I am encountering the error message "Utils is not defined" while attempting to generate a chart using chart.js

Attempting to replicate the example provided in chart.js documentation : link to example Unfortunately, I am encountering the error: Uncaught ReferenceError: Utils is not defined Despite its simplicity, I am struggling to identify the issue...! ...

Using Vue to perform multiplication on data table entries

Is there a way I can use Vue.js to multiply values in a table? The values provided are for 100g of the product. For example, if I input 200g, I would like the values to double: 318kcal, 12 fat, 48 carbs, 8 protein, and 2% iron. Similarly, inputting 50g sho ...

What's the better approach for creating Maps and Sets in ES6: relying on a compiler or leveraging syntactic sugar?

It has always baffled me why we are unable to write ES6 Maps in the following way: new Map({ ['ArrayAsKey']: {foo:bar} }) Is there a workaround for this limitation? Or perhaps a technique that enhances the experience of utilizing these mode ...

Search for a specific string within a JSON object using Node.js

Within my JSON file, I need to determine if a specific string exists. For example: let testjson =require('./jsontest.json'); let string= 'abcd'; I want to check if abcd is present within the JSON object. The structure of my JSON file ...

waiting for deferred to complete in esri javascript api before continuing with code execution - labelPoints

I'm encountering an issue with obtaining my labelPoints before completing the rest of my code. It seems to be related to a deferred/callback problem that I can't quite grasp, and I couldn't find many examples using the esri javascript api. ...

Is there a way for me to extract a smaller segment from an ID label?

I am working on a web development project and I have a set of buttons within a specific section. Each button has an id in the format of #balls-left-n, where n ranges from 1 to 15. My goal is that when a user clicks on one of these buttons, I want to extra ...

Updating ngModel using the value retrieved from a service call

After experiencing dissatisfaction with Angular's form validation, I decided to develop my own solution. However, I have encountered a perplexing issue that has me at a loss. Here is how my setup looks: I employ a directive to create a new form. Th ...

Having trouble sorting data-text values that include colspan cells

Latest Update: Encountered an issue with incorrect sorting and frozen sortings when dealing with a cell containing the colspan attribute. Refer to https://jsfiddle.net/2zhjsn31/12/ where the problem arises for the date 2018-06-24 On https://jsfiddle.n ...

Managing Timezones in DateTime in C#, JSON, and Android

I am facing an issue with date transformation within a SQL Server database. The original date appears as 2012-01-10 00:00:00.000, but when converted to JSON format, it changes to "/Date(1326150000000+0100)/". When I try to extract only the milliseconds in ...

When utilizing an API to render text into a div, the offsetHeight function may return 0

I'm working with a div that displays text fetched from an API call. I'm trying to implement a See more button if the text exceeds 3 lines. Here is my approach: seeMore(){ this.setState({ seeMore: !this.state.seeMo ...

What are the various ways to display time zone in a different format?

I need to display the timezone in a unique manner. I have captured the user's timezone in a variable called timeZone, which currently returns the value as Asia/Calcutta. console.log(timeZone) // "Asia/Calcutta" Is there a way to showcase the timezon ...