Difficulty encountered with personalized d3.js visualization

I'm currently diving into the world of d3.js and aiming to develop a visualization similar to the example image I've attached in the link below.

http://jsfiddle.net/mike_ellan/37PYJ/

While I have a good grasp on creating and binding text elements, I am facing some challenges when it comes to working with this specific data structure. Unfortunately, I do not have the flexibility to request a different JSON format, so I need to figure out how to map it effectively. Here is the initial data:

var consumption = [
{
    "fruits": [
        {
            "year":"2011",
            "apples":"213",
            "oranges":"176",
            "pears":"987"
        },
        {
            "year":"2012",
            "apples":"199",
            "oranges":"234",
            "pears":"672"
        }
    ]
}
];

My strategy for handling the years is to create a two-row/column table and dynamically add columns for each year based on the JSON data. Any insights or tips on how I can approach this task would be greatly appreciated!

Answer №1

Hey Mike, here's a simple way to create the graph.

Setting Up Columns and Adding Headers

// Group Columns
var columns = groupColumn.selectAll("g")
                                    .data(consumption[0].fruits)
                                    .enter()
                                    .append("g")
                                    .attr("class", function(d,i) { return "column - " + i });
              // Add year header
              columns.append("text")
                             .attr("transform", function(d,i) { return "translate(" + i*(width/2) + "," + height/2 + ")"; })
                             .text(function(d) {return d.year });  

Creating Rows and Inserting Data Fields

 // Insert row
var groupRow = columns.append("g")
                             .attr("class", "fruits")
                             .attr("transform", function(d,i) { return "translate(" + i*(width/2) + "," + height/2 + ")"; })

 // Insert data fields in rows
var rows =   groupRow.selectAll("circle")
                               .data(function(d) {return d3.entries(d).filter(function(d) { return d.key !== "year"; })})
                               .enter()
                               .append("circle")
                                    .attr("cx",function(d,i){ return (60 * i) + 30 } )
                                     .attr("cy",50)
                                     .attr("r",25)
                                     .attr("fill", function(d){ 
                                        if(d.key === "apples"){ return "red" }
                                        else if (d.key === "oranges"){ return "orange" }
                                        else if (d.key === "pears"){ return "green" }
                                     })

Adding Text to Data Fields

var text = groupRow.selectAll("text")
                            .data(function(d) {return d3.entries(d).filter(function(d) { return d.key !== "year"; })})
                            .enter()
                            .append("text")
                                   .attr("dx", function(d,i){ return (60 * i) + 20 })
                                   .attr("dy", 55)
                                   .attr("fill", "white")
                                   .text(function(d) {return d.value});

Check out the full code http://jsfiddle.net/jmeza/37PYJ/3/

This example covers the initial steps, more to come...

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

What is preventing me from accessing arguments.callee within this function in sloppy mode?

In attempting to retrieve the arguments.callee property in the following basic function, I encountered an error preventing me from doing so. function foo(a = 50, b) { console.log(arguments.callee); } foo(10, 50); Why is this issue occurring? It appe ...

Transmitting a Custom JS Object via Vue Router

Stuck! I’ve been hitting my head against the wall for hours trying to figure this out... Technologies Utilized: Vue (v3.0.0) Vue-Router (v4.0.0-0) Bootstrap (v5.1.1) The Objective: I have two pages (Home.vue, MetaUpdate.vue) and one component (Docum ...

Using jQuery to retrieve child elements and assign numerical values to them

Looking for a jQuery function that can apply different CSS attributes to children elements of a div. <div class="container"> <div class="autogenerated-div"></div> <div class="autogenerated-div"></div> <div class="aut ...

Exploring the use of global variables in React

Welcome to my React learning journey! I've encountered an issue while trying to access a global variable exposed by a browser extension that I'm using. Initially, I attempted to check for the availability of the variable in the componentDidMount ...

fetching a set of data entries from an entity on dynamic CRM platform utilizing the REST API along with asynchronous JavaScript and XML

Seeking to display all accounts from the account entity in an alert box by making an ajax call to the Service OrganizationData.svc. The post method works fine for adding an account, but when trying to retrieve all accounts using GET, I encounter some diff ...

Tips for altering promises within nested for loops?

Presented below is a complex function that aims to extract model variants from a csv file, which are stored as strings in an array. The path of this csv file depends on information obtained from other csv files, hence the need for looping. The csvService. ...

The PHP function is returning an undefined value in JavaScript

I feel like there must be a simple solution to this problem that I just can't seem to find. Everything related to PHP search functions and queries is functioning properly, except for the fact that the data isn't displaying correctly in the text a ...

I am wondering about the proper method for deleting multiple records simultaneously in Ember Data

My current challenge involves managing a list of record IDs, such as [1, 20, 20]. The process of individually querying and deleting each item is proving to be quite inefficient. store.findRecord('post', 1).then(function(post) { post.deleteRec ...

Is there a way to make an iPhone Select List that only allows for a single selection instead of multiple

I seem to be encountering a problem where the select dropdowns on my iPhone, bound in knockout, are allowing users to select multiple items. The select scrollwheel pops up and I'm wondering if there's a way to make it only allow single values. Be ...

Tips for choosing the following row in an Angular user interface grid

How can I deselect the currently selected row and select the one that follows it by clicking a button? I am using AngularHotkeys.js for this purpose. It gets even more complicated because I can sort the table with different columns. It would be helpful to ...

Using ng-bind-html within a ng-repeat loop

Currently, I am working on developing a custom autosuggest feature where a web service is queried with a search term to retrieve a list of suggestions that are then displayed. My main obstacle lies in trying to highlight the matching term within the sugges ...

Server has provided additional attributes: "fdprocessedid" was not updated in the input for both Graphql and JSON

I'm currently using Next.js, TypeScript, and GraphQL. I am working on adding data to a local JSON file through Apollo Server but encountering two issues. One issue is that I'm receiving the warning "Extra attributes from the server: fdprocesse ...

Storing a string in a variable within Typescript

Attempting to read an XML file in Typescript using some JavaScript code, with the goal of adding the text content to a local variable. The code snippet is as follows: import { Injectable } from '@angular/core'; @Injectable() export class Jsonre ...

What is the best way to display Json data in a UITableView using Swift 4?

My code structure looks something like this: struct Excercise: Codable { let excerciseID: String let excerciseName: String let description: String let intensity: Int } Next, I have the variable defined as: var excercistList = [Excercis ...

Encountering a CORS issue while attempting to make a GET request to an API in an

Looking to retrieve HTML data from a website using an API. The target URL is: https://www.linkedin.com/ Trying to fetch the HTML page as text from this specific URL. Here's what I attempted: getData() { const api = "https://www.linkedin. ...

Encountering a localhost redirection loop due to NextJs rewrites

Here is the current configuration in my next.config.js file: // next.config.js module.exports = { async rewrites() { return [ { source: '/results', destination: 'https://mywebsite.com/results', }, ...

Accepting information from JavaScript in PHP

Here's a practical example below, I hope it helps others in their learning process! Currently, I am utilizing AJAX in javascript to transmit a JSON string to PHP. My knowledge of AJAX, javascript, and php is limited, so getting started with this pro ...

Obtain an array promise containing objects, followed by looping through each object

I am in the process of creating an array named pw_array, copying the contents of pw_subscribers into that array, and then adding new key value pairs to each object in the pw_array from the second promise. I am relatively new to working with promises and st ...

Obtaining the values from an NSArray in JSON format

I have been utilizing JSON Accelerator from Nerdery for converting JSON String to Obj-C classes. However, I'm encountering issues with retrieving the values from a JSON NSArray. Below is the JSON string: { "status": { "code": 200, ...

Why are the random colors blending into the image?

After watching a tutorial on the YouTube channel Online Tutorials titled "Change Image Color Vanilla JavaScript," I am confused as to why some random colors from the click event are overlapping the image instead of just changing the color of the cat's ...