The x-axis is represented by JSON keys, while the y-axis is represented by

I am currently attempting to replicate a graph that was originally made in Excel.

Here is the code I have written so far:

    var data = [
      {
        'FB':4,
        'Mv':4,
        'CB':5,
        'SL':3,
        'CH':2,
        'OT':2,
        'Ctrl':6,
        'Cmd':6,
        'Del':5,
        'AA':6,
       },
      {
        'FB':2,
        'Mv':3,
        'CB':4,
        'SL':5,
        'CH':4,
        'OT':3,
        'Ctrl':5,
        'Cmd':6,
        'Del':6,
        'AA':5,
       },
       etc...
    ];

    var margin = {top:10, right:10, bottom:30, left:40},
        width = 600 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

    var xScale = d3.scale.ordinal()
        .domain(d3.keys(data[0]))
        .rangeRoundBands([0, width]);

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

    var xAxis = d3.svg.axis()
        .scale(xScale)
        .orient('bottom')
    var yAxis = d3.svg.axis()
        .scale(yScale)
        .orient('left')
        .ticks(3);

    var svg = d3.select('#d3Stuff').append('svg')
        .attr('width',width + margin.left + margin.right)
        .attr('height',height + margin.top + margin.bottom)
        .style('border','1px solid black')
        .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis)
        .append("text")
        .attr("class", "label")
        .attr("x", width)
        .attr("y", -6)
        .style("text-anchor", "end");

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("class", "label")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end");

I am struggling with displaying circles for the values in the data object. The goal is to align these circles with the keys on the x axis. Once I can display the initial values, I can proceed with calculating min/max/avg.

So far, this is what the code has produced:

Any assistance would be greatly appreciated!

Answer №1

To determine the x position of any circle, you can utilize the ordinal scale along with the corresponding keys from the ordinal domain. For instance, x("FB"), x("Mv"), and so forth.

In order to create the circles, it is necessary to bind them to an array in the conventional d3 manner, employing the enter, update, exit methodology.

Given that your data is structured as a hash rather than an array, it must first be converted into array format. This can easily be accomplished using d3.map() alongside theData (it's advisable to remove the unnecessary array brackets [] enclosing the hash inside theData):

d3.map(theData[0]).entries()
/* returns [
  {
    "key": "FB",
    "value": 4
  },
  {
    "key": "Mv",
    "value": 4
  },
  {
    "key": "CB",
    "value": 5
  },
  {
    "key": "SL",
    "value": 3
  },
  {
    "key": "CH",
    "value": 2
  },
  ...
]"

Once you have this associative array, you can proceed with the customary data(...) binding, append the circles, and then position them utilizing something similar to:

.attr("x", function(d) { return x(d.key); })

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

Using Javascript to automatically replace content when the page is loaded

Having trouble with my fullCalendar jquery calendar and the 'eventClick' method. When I click on an event, the URL is getting encoded incorrectly. For example, I'm trying to pass a Wordpress URL like this: http://sitedomain.com/?post_type= ...

Looking to implement a delay in the model popup using Pure JavaScript

Looking for a method to implement a delay in the popup... I've tried a few solutions without success. What's the secret to adding a delay to the modal below? Any help is greatly appreciated. var modal = document.querySelector(".modal"); var t ...

Dynamic HTML element

I created an input number field and I want to dynamically display the value of this field in a container without having to refresh the page. I am currently using ajax for this purpose, but unfortunately, I still need to reload the page. HTML: < ...

The `Target closed` error in Playwright Library is triggered solely by the closing of either the `context` or `browser`

The code snippet below showcases a Node.js script that leverages the Playwright Library for browser automation (not Playwright Test) to extract data from a local website and display the results in the terminal. The challenge arises when the script encounte ...

Improved Approach for Replacing if/else Statements

I'm looking to streamline the controller used in my SQL command for filtering records based on specific criteria. The current approach below is functional, but not without its limitations. One major issue is scalability - adding more criteria in the f ...

Troubleshooting issue: Bootstrap button onclick function not firing

My node express app is using EJS for templating. Within the app, there is a button: <button type="button" class="btn btn-success" onclick="exportWithObjectId('<%= user.id %>')">Export to csv</button> Accompanying the button i ...

Setting state back to default following the conditional rendering of a React component

Whenever the save button is clicked, I aim to display a snackbar component by updating the showSnackbar state to true. To achieve this in React, it's just a simple conditional check in the main render method. The snackbar I'm using here automatic ...

The jQuery prop("disabled") function is not operating as expected

Although I've seen this question answered multiple times, none of the suggested solutions seem to be working for my specific example. Hopefully, a fresh set of eyes can help me figure out what's going wrong. Even after adding alerts to confirm t ...

Creating a double-layered donut chart with Chart.js

I'm attempting to create a unique pie chart that illustrates an array of countries on the first level and their respective cities on the second level. After modifying the data in a JSON file to align with my goal, it doesn't seem to be working a ...

The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file. Here is the script: var loader = document.getElementById("ld"); w ...

Exploring the effectiveness of testing Svelte components

Looking to test a component that utilizes a third-party module without mocking the imported components? Check out this example: // test.spec.ts import Component from "Component"; describe('Component', () => { test('shoul ...

I am interested in incorporating pinia state management into my Vue 3 project

I'm currently working on implementing pinia state management in Vue 3, but I've encountered the following error: Module not found: Error: Can't resolve 'src/stores/cart' in 'C:\Users\Ali Haider\theme-project&b ...

Incorporating Checkbox Value into Textbox with classic ASP and jQuery

Here is a glimpse of the code I've written: response.write "<th align=left><font size=2>" response.write "1. <input type=checkbox class='checkboxes' value='ORG'>Organization" response.write "</font> ...

What causes a browser to redirect when trying to update the value of the alt field in a Wordpress media image?

Attempting to create a bookmarklet for the Wordpress image gallery manager that triggers the sidebar when an image is clicked. The sidebar contains fields for alt text (input), legend, and description (both textarea). <a href="javascript:var t=document ...

Synchronizing code paths that involve both ajax and non-ajax functions can be achieved by

My website features a basket functionality where users can enter an author's name and see the available books. After selecting desired books, they have the option to click on another author for more selection. The displayed list includes books by Step ...

Having issues with Json stringification and serializing arrays

Having an issue with Json when using serializeArray. An example of my HTML form: <form action="" method="post" name="myForm"> ID: <input type="text" name="id" /><br/> State (XX): <input type="text" name="state" /><br/> <p ...

Unable to retrieve scope variable within AJAX call

I am currently in the process of running a loop function that contains an AJAX request within it. However, I am facing difficulties with the success function on the AJAX not being able to access a counter variable outside of the loop function. var upda ...

Implementing code to scroll and play multiple videos simultaneously using JavaScript and jQuery

This solution currently only works for one video, but it needs to be able to handle multiple videos (TWO OR MORE) <html> <head> <script src="https://code.jquery.com/jquery-1.8.0.min.js" integrity="sha256-jFdOCgY5bfpwZLi ...

Struggling to display a navigation menu on angular 1 with complex nested json structure

I have set up a navigation bar using JSON data fetched by an Angular service. Everything is working fine with my service and controller, but I am facing difficulty in displaying the nested JSON data in my view. Here is the JSON data: { "menu": [ ...

Sequelize: Establishing association upon saving without the need to retrieve another object

Suppose I have two tables, parent and child, where the parent has multiple children. They are properly mapped in Sequelize. Now, I need to add a new child to an existing parent. However, I do not have access to the parent instance, only its id. I am aw ...