Visualizing JSON data on D3.js graph axis

Below is a snippet of JSON data that I successfully plotted on a d3js graph, using it as the x and y axis:

var data = [
{
"count": "202",
"year": "1590"
},
{
"count": "215",
"year": "1592"
}, 
{
"count": "179",
"year": "1593"
}
];

Now, I am facing a challenge in plotting the following JSON:

var data = {
"count": [202, 215, 179],
"year": [1590, 1592, 1593]
};

Here is the code I used to plot the axes for the initial JSON data:

/******Sample JSON data being plotted********/
var data1 = {
"count": [202, 215, 179],
"year": [1590, 1592, 1593]
};

var data = [
{
"count": "202",
"year": "1590"
},
{
"count": "215",
"year": "1592"
}, 
{
"count": "179",
"year": "1593"
}
];

/*************************************************/

/*******************Actual Implementation begins here*******************/

var vis = d3.select("#visualisation"),
WIDTH = 600,
HEIGHT = 400,
MARGINS = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
xRange = d3.scale.linear().range([MARGINS.left, WIDTH - MARGINS.right]).domain([d3.min(data, function (d) {
return (parseInt(d.year, 10) - 5);
}),
d3.max(data, function (d) {
return parseInt(d.year, 10);
})]),
yRange = d3.scale.linear().range([HEIGHT - MARGINS.top, MARGINS.bottom]).domain([d3.min(data, function (d) {
return (parseInt(d.count, 10) - 5);
}),
d3.max(data, function (d) {
return parseInt(d.count, 10);
})]),

xAxis = d3.svg.axis() // generate an axis
.scale(xRange) // set the range of the axis
.tickSize(5) // height of the ticks
.tickSubdivide(true), // display ticks between text labels
yAxis = d3.svg.axis() // generate an axis
.scale(yRange) // set the range of the axis
.tickSize(5) // width of the ticks
.orient("left") // position text labels on the left
.tickSubdivide(true); // display ticks between text labels 

function initialize() {
vis.append("svg:g") // add a container for the axis
.attr("class", "x axis") // add classes to style it
.attr("transform", "translate(0," + (HEIGHT - MARGINS.bottom) + ")") // move it into position
.call(xAxis); // add the axis to the visualization

vis.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(" + (MARGINS.left) + ",0)")
.call(yAxis);
}
initialize();

Check out the demonstration on jsfiddle here

Answer №1

Update xRange and yRange

   xRange = d3.scale.linear()
               .range([MARGINS.left, WIDTH - MARGINS.right])
               .domain([d3.min(data.year, function (d) {
                        return (parseInt(d, 10) - 5);
                }),

           d3.max(data.year, function (d) {
               return parseInt(d, 10);
          })]),

   yRange = d3.scale.linear()
              .range([HEIGHT - MARGINS.top, MARGINS.bottom])
              .domain([d3.min(data.count, function (d) {
                       return (parseInt(d, 10) - 5);
              }),

            d3.max(data.count, function (d) {
               return parseInt(d, 10);
            })]),

VIEW THE DEMO HERE

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

Tips for integrating CSS keyframes in MUI v5 (using emotion)

Hey there! I'm currently working on adding some spinning text, similar to a carousel, using keyframes in my React app. The setup involves MUI v5 with @emotion. Basically, I want a "box" element to show different words every few seconds with a rotating ...

Exclude the map entry from displaying in a JSON document

I am currently working with the following endpoint: @RestController @RequestMapping(value = "/info") public class InfoEndPoint { .... @Autowired public InfoEndPoint(....) { .... } @RequestMapping(method = RequestMethod.GET) ...

Exploring the JSON structure within MongoDB

I am looking to build a Json tree using data from 3 collections retrieved from MongoDB. For instance: https://i.sstatic.net/aVdYj.png Each area can have connections to other areas, spaces can be connected to areas and other spaces, and dashes are linked ...

Unleashing the potential of an endless animation by incorporating pauses between each iteration

I am trying to create an infinite animation using animate css but I want to add a delay between each iteration. After exploring various options, I first attempted to achieve this using plain JavaScript. Here is the HTML snippet: <div id="item" class= ...

Transforming the color of a globe from black to white with gio js

After searching for a solution to change the color of a Three.js globe, I came across a link that didn't work as expected: Change the color of a Three.js globe. My goal is to change the globe color from black to white using . I attempted to use the f ...

Creating an image gallery with animated effects: A step-by-step guide

I am looking to develop a creative image gallery with animated effects. I also want to include panels and hyperlinks for each image, similar to the functionality on this website: http://www.microsoft.com/en-lk/default.aspx Can anyone guide me on how to ac ...

Implementing pagination in Firestore using React-Redux

I'm currently working on implementing pagination with Firebase and React Redux Toolkit. I've grasped the logic behind it, but I'm facing challenges when integrating it with Redux. Initially, my approach was to store the last document in the ...

How come outerHTML retrieves <!-- --> comments?

I came across a jsfiddle link that showcases the collection of outerHTML for elements with a class='active'. Surprisingly, even when certain parts of the HTML are commented out like this: <!-- <div>'Some inner text'</d ...

Which specific web framework supports the functionalities of Microsoft Dynamics CRM 2011?

Is there an SDK available from Microsoft that can help me create a web product with similar rich ajax features as Microsoft Dynamics CRM 2011? I have considered using Microsoft SharePoint Foundation 2010, but I am concerned that it is designed for small o ...

Convert JSON string to a C# list for a dropdownlist

I am working on a Windows Form application where I need to deserialize a JSON string obtained from a web address in order to extract two specific values. Can someone guide me on how to achieve this? Here is the code snippet I have for fetching the JSON st ...

creating dynamic data objects in ajax calls

https://jsfiddle.net/c7n34e3x/1/ from data, data1, and data2, only data is functioning, but it lacks dynamism. This method works as intended. var settings = { "async": true, "crossDomain": true, "url": "https://domain/api/v2/playlists/", ...

Verifying whether every value in the X array is present in the Y array or not

Currently, I am working with two arrays: const arrA = [1, 2, 3, 4, 5]; const arrB = [1, 2, 3, 4, 5, 6, 7, 8, 9]; My goal is to determine if all elements in array A exist in array B. Here are a few scenarios for better clarity: const arrA = [1, 2, 3, 4, ...

Activate the saturation toggle when a key is pressed in JavaScript

I am trying to modify a script that currently toggles the value of a variable when a key is pressed and then lifted. Instead of changing the variable value, I would like to adjust the saturation of the screen based on key presses and releases. How can I ac ...

Is it feasible to utilize the return value of an Async call to display or conceal an alert message?

Before this gets closed as a duplicate, I have searched through numerous threads on the forum that do not address my specific question. Please take the time to read. Here is the scenario: when a user clicks a button, JavaScript needs to validate whether t ...

Checking if the current time falls within a specific time range, without taking the year into account, using Javascript

I am looking to add a special feature using JavaScript. I would like to change the background images of my webpage to ones related to Christmas during the holiday week, and have it repeat every year. How can I determine if the current date and time fall ...

Troubleshooting app.use in Next.js and express.js: Understanding the issue

Currently, I am working on a project using next.js along with a custom server (express.js). In my API endpoints, I want to utilize some middlewares (such as const attachUser), but strangely I am facing issues when trying to use app.use. The code seems to ...

A guide on extracting individual Json fields and assigning them to separate variables

I have a JSON object that I need to break down into individual fields and then use each field separately. However, the code I wrote below is not functioning correctly and returns "undefined" in the alert message. This is my code snippet: $( document ).r ...

The execution of dynamically generated Javascript in JSON format, returned through AJAX, is prevented when it is appended

Recently, I encountered an issue on my webpage where I made an AJAX request to a PHP script. The PHP script responded with a valid JSON object and set the Content-type header to application/json. After examining the JSON format using console.log(JSON.stri ...

Guide to implementing if else statements with Protractor

I am facing some unusual situations and I'm not quite sure how to address them. As a newcomer to testing, I've been tasked with testing a website's cart function for proper functionality. The challenge arises when we add a certain number o ...

sending data to Google Maps and updating it

OPERATING SMOOTHLY My requirement is to display only the items that match the entered username and password. I am unable to pass PHP variables to JavaScript in order to query the database and update the map. The following code is functioning correctly (p ...