Utilizing only a fraction of my dataset, I created a barplot in D

My d3.js barplot is based on JSON data with 12 elements. The 'fpkm' value determines the bar height, but only half of the elements are showing up correctly.

When I use the data callback function in d3, it only returns values for the first half of the elements, resulting in only 6 rows being displayed on the plot.

A fiddle showcasing this issue can be found here: http://jsfiddle.net/z9Mvt/

I'm struggling to understand why only half of the JSON elements are being utilized in my visualization.

Here's the HTML and JavaScript code snippets:

<div align='center' id="GECGplot" style='width:98%;text-align:center;'></plot>
// JavaScript code snippet
// Define dataset
var plotData = [{}, {}, ...]; // Your JSON data here

// Set up SVG dimensions
var w = 700;
var h = 300;
var barPadding = 1; 
var margin = {top: 40, right: 10, bottom: 20, left: 10};

var xScale = d3.scale.linear().
  domain([0, 20]).
  range([0, h]);

// Create SVG element
var svg = d3.select("#GECGplot")
            .append("svg")
            .attr("width", w)
            .attr("height", h);

// Generate bars
svg.selectAll("rect")
   .data(function(d, i) {
        return plotData[i].nodeData.fpkm;
    })
   .enter()
   .append("rect")
   .attr("x", function(d, i) {
        return i * (w / plotData.length);
    })
   .attr("y", function(d, i) {
        return h - (plotData[i].nodeData.fpkm * 50);  
    })
   .attr("width", w / plotData.length - barPadding)
   .attr("height", function(d, i) {
        return plotData[i].nodeData.fpkm * 50;  
    })
   .attr("fill", function(d, i) {
        return "rgb(0, 0, " + (plotData[i].nodeData.fpkm * 50) + ")";
    });

// Add labels
svg.selectAll("text")
    .data(function(d, i) {
        return plotData[i].nodeData.fpkm;
    })
    .enter()
    .append("text")
    .text(function(d, i) {
        return plotData[i].nodeData.fpkm;
    })
    .attr("font-family", "sans-serif")
    .attr("font-size", "11px")
    .attr("fill", "white")
    .attr("text-anchor", "middle")
    .attr("x", function(d, i) {
        return i * (w / plotData.length) + (w / plotData.length - barPadding) / 2;
    })
     .attr("y", function(d, i) {
        return h - (plotData[i].nodeData.fpkm * 50) + 14; 
    });

Answer №1

In this solution, the array "children" is bound to the rectangle elements so there is no need for the argument 'i' to access the necessary value.

Furthermore, I suggest using d3.scale.ordinal() for the x axis instead of calculating it directly from the data as it offers more flexibility.

Check out this example on JSFiddle for a visual representation.

svg.selectAll("rect")
    .data(plotData)
  .enter().append("rect")
    .attr("x", function(d, i) {return i * (w / plotData.length);})
    .attr("y", function(d) {
      return h - (d.nodeData.fpkm * 50);  //Height minus data value
    })
    .attr("width", w / plotData.length - barPadding)
    .attr("height", function(d, i) {
      return d.nodeData.fpkm * 50;  //Just the data value
    })
    .attr("fill", function(d, i) {
      return "rgb(0, 0, " + (d.nodeData.fpkm * 50) + ")";
    })

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

access various paths to distinct iframes

<?php // Specify the directory path, can be either absolute or relative $dirPath = "C:/xampp/htdocs/statistics/pdf/"; // Open the specified directory and check if it's opened successfully if ($handle = opendir($dirPath)) { // Keep readin ...

Tips for showcasing live data in Material-UI's table component

My challenge lies in displaying tabular data fetched from an API in a Material-UI Table. Specifically, I aim to exhibit the fields id and name stored within groups. How can I achieve this result? Beneath is my current code snippet which runs without error ...

What is the process for uploading an image encoded in base64 through .ajax?

I am currently working with JavaScript code that successfully uploads an image to a server using an AJAX call. Here is the ajax call snippet that is functioning properly. $.ajax({ url: 'https://api.projectoxford.ai/vision/v1/analyses?', ...

The absence of variable declaration in a 'for...of' loop is functional in .js files but does not work in

index.js let items = [{ item: 'apple' }, { item: 'banana' }, { item: 'orange' }]; for (item of items) { console.log(item); } Execute using node $ node index.js { item: 'apple' } { item: 'banana' } { ...

Modify the material of all other models to match the material of the selected model

I've been tinkering with the vertex shader for 3D models, but I'm running into an issue where I can't seem to change all other models' materials to match the selected model's material. Each viewport contains 4 models, and when I se ...

Encountering an unusual issue: Unable to access undefined properties (specifically 'get')

I'm struggling to get the order history screen to display the order history of a specific user. Every time I navigate to the path, I encounter the error mentioned in the title. I double-checked the path for accuracy and made sure there are no spelling ...

Leveraging the FileReader API within a Vue.js component function

I'm working on a Vue.js file picker that needs to display previews of selected files. To accomplish this, I am utilizing the FileReader API to read user-selected files as data URLs using the readAsDataURL method of the FileReader object. However, I&a ...

Choose a property and its corresponding value at random from a JavaScript object

Recently delving into the world of Javascript and seeking guidance. I set out to create a random picker from an array and succeeded with the following setup: var movie = ["star wars", "lotr", "moonlight", "avengers"] function newMovie() { var randomNu ...

What is the best way to retrieve the transpiled string from babel-core?

I've been attempting to utilize babel with npm and it seems like the necessary package is babel-core. My goal is to provide it with a string of ES6 code and receive a transpiled code string in return. It sounds simple enough, but I'm having troub ...

"The ASP.NET MVC controller is encountering an unknown error when attempting to return a JSON list of objects of type T

In an attempt to return the List collection from the controller to the ajax function as a JSON string, I am encountering issues. The necessary JSON data is being generated, but when debugging, I only see an "undefined" error for the JSON response in the br ...

Vue- async function results in a Promise object with a status of <pending>

Hey everyone, I could use some assistance with my Vue code. Here's the issue: I'm attempting to retrieve data (specifically anime) from an online anime API. In my project, I have two files: Anime.vue (the view page) and getAnime.js (which house ...

Dealing with substantial JSON data in Scala

I am facing a challenge with multiple files that contain arrays which need to be concatenated. The issue is that these files are numerous and quite large, with each one being around 5mb in size, leading to a total of over 100mb. My attempt using Pla ...

Guide to inserting an HTML file into an article's content

After downloading an extension from freefrontedit and uploading it to my server in the directory /accordeon, I successfully accessed it by pointing my browser to . However, I am now faced with the challenge of loading the index.html into my Joomla article ...

The JSON validator effectively verifies all types of string inputs

Schema for Root: { "$schema": "https://json-schema.org/draft/2020-12/schema", "properties": { "deviceId": { "description": "Unique identifier of the device in UUIDv4 format& ...

Loop through the JSON object at a depth of three levels

Can someone please help me with this issue that's been bothering me? I'm currently working with Facebook's Graph API to access data. I need to find out how to retrieve the application name. { "data": [ { "messag ...

Determine the numerical worth of a JSON entity

In my possession is a JSON Object containing the following data. { "1":[{"count":1,"sessionID":"111","timeLogin":2}], "2":[{"count":1,"sessionID":"222","timeLogin":3}], "3":[{"count":1,"sessionID":"333","timeLogin":3}], "4":[{"count ...

In Laravel, pagination displays tables that contain some values from the paginate() function, but not all values

Currently testing my API in Postman, it successfully returns values but not pagination data. http://localhost/api/v1/projects-data //This is api Here is the image of the data that is returned to Postman: I have placed the route code in api.php Route::ge ...

Securing child paths in Vue.js

Having trouble protecting child routes from parent routes, facing some issues export default new Router({ routes: [ //frontend routes { {path: 'auth', component: Auth, children: authroutes, beforeEnter: (to, from, n ...

Looping through color transitions upon hover using CSS

I am trying to create a color transition effect on hover, where the background changes from yellow to red and then back to yellow in a loop. I'm having trouble figuring out how to make this transition repeat continuously. Do I need to incorporate Java ...

Creating interactive JSON objects through the use of JavaScript and AngularJS

When using AngularJS to build a dynamic JSON from server data, I encountered an issue where my current declaration only works if the server data contains one item in the object array. How can I modify this to handle multiple items dynamically? $scope.it ...