Incorporate Y-axis titles onto D3 bar chart using the attribute 'name' from JSON data

While following the tutorial on creating a bar chart, I encountered an issue in step three. The bars are rotated to columns, but I am struggling to iterate over a JSON dataset and add Y-axis labels for each bar using the name attribute from the returned JSON data.

You can view my code on jsfiddle here

Below are the code samples:

The JSON data loaded:

[
    {
        "name": "1-30 days",
        "value": "22"
    },
    {
        "name": "31-60 days",
        "value": "14"
    },
    {
        "name": "61-90 days",
        "value": "1"
    }
]

My D3 code:

var width = 420,
    barHeight = 20;

var x = d3.scale.linear()
    .range([0, width]);

var chart = d3.select(".chart")
    .attr("width", width);


d3.json("<?=APP_PATH?>/query", function(error, data) {
  x.domain([0, d3.max(data, function(d) { return d.value; })]);


  chart.attr("height", barHeight * data.length);

  var bar = chart.selectAll("g")
      .data(data)
    .enter().append("g")
      .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; });

  bar.append("rect")
      .attr("width", function(d) { return x(d.value); })
      .attr("height", barHeight - 1);

  bar.append("text")
      .attr("x", function(d) { return x(d.value) - 3; })
      .attr("y", barHeight / 2)
      .attr("dy", ".35em")
      .text(function(d) { return d.value; });
});

function type(d) {
  d.value = +d.value; // coerce to number
  return d;
}

Answer №1

When it comes to turning the bars into columns, I may need more clarity. However, to achieve the desired outcome, simply include another batch of text elements within the current selection:

bar.append("text")
  .attr("x", 0)
  .attr("y", barHeight / 2)
  .attr("dy", ".35em")
  .attr("dx", "-1em")
  .style("fill", "black")
  .text(function(d) { return d.name; });

You can find a complete demonstration here. I've also adjusted the position of the bars to accommodate the new labels.

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

Sending data through props to components that can only be accessed through specific routes

File for Router Configuration import DomainAction from './components/domainaction/DomainAction.vue' ... { path: '/domainaction' , component: DomainAction }, ... Linking to Routes using Router Links ... <router-link to="/domainact ...

In Vue(tify), transitions require children to have keys, but in this case, there are no tags present as children

Trying to implement a transition on a list using Vue and Vuetify, but encountering the error message vue.runtime.esm.js?2b0e:619 [Vue warn]: <transition-group> children must be keyed: <v-card> I attempted the Vuetify approach <v-fade-transi ...

Next.js allows you to create a single page that corresponds to the root path '/' as well as a dynamic route '/param'

I have a single-page website built with Next.js. The home page, which displays a list of products, is located at route / and the corresponding code can be found in pages/index.js. Each product has an id, allowing users to jump directly to it using /#produc ...

Determine the position of the cursor in an editable span

Is there a way to add text at the cursor position in an editable span when a button is clicked? The span contains multiple lines of text and HTML tags. [Take a look at this example on JSFiddle](http://jsfiddle.net/8txz9sjs/) ...

Guide on setting a wait while downloading a PDF file with protractor

As I begin the download of a pdf file, I realize that it will take more than 2 minutes to complete. In order to verify if the file has successfully downloaded or not, I will need to wait for the full 2 minutes before performing any verification checks. C ...

The propagation of SVG events from embedded images via the <image> elements

I'm currently developing a diagramming tool using HTML, CSS, and Javascript with SVG for the drawing canvas. This tool consists of predefined "building blocks" that users can place on the canvas, rather than allowing free-hand drawing of shapes. Each ...

The value returned by EntityRecognizer.resolveTime is considered as 'undefined'

In my bot's waterfall dialog, I am utilizing the LuisRecognizer.recognize() method to detect datetimeV2 entities and EntityRecognizer.resolveTime() to process the response. Here is an example of how I have implemented it: builder.LuisRecognizer.recog ...

Error: export keyword used incorrectly

Currently, I am in the process of developing an npm package called foobar locally. This allows me to make real-time changes and modifications without the need to constantly publish and unpublish the package, which greatly improves my development efficiency ...

Exploring AngularJS $compile and the concept of scoping within JavaScript windows

I've encountered a scoping issue with the use of this inside an angular-ui bootstrap modal. The code below functions perfectly outside of a modal, but encounters problems when run within one: var GlobalVariable = GlobalVariable || {}; (fun ...

The Eclipse Phonegap framework is experiencing difficulty in loading an external string file with the jquery .load function

A basic index.html file has been created to showcase a text string from the test.txt file by utilizing the .load function from the jQuery library. The goal is to insert the textual content into an HTML (div class="konten"). The provided HTML script looks ...

What are the benefits of using `observer` over `inject` when passing data to a React component in MobX?

After reading MobX documentation, it appears that using observer on all components is recommended. However, I have discovered that by utilizing the inject method, I am able to achieve more precise control over which data triggers a re-render of my componen ...

Clever method for enabling image uploads upon image selection without needing to click an upload button using JQuery

Is there a way to automatically upload the file without having to click the upload button? Detail : The code below shows an input field for uploading an image, where you have to select the file and then click the "Upload" button to actually upload it: & ...

Encountering a Uncaught TypeError when attempting to split an undefined property, but issue is limited to certain pages

Recently, I've encountered an issue with iziModal on specific pages where I'm getting an error message. The error I'm facing is: Uncaught TypeError: Cannot read property 'split' of undefined at r.fn.init.t.fn.(anonymous fu ...

The text box remains disabled even after clearing a correlated text box with Selenium WebDriver

My webpage has two text boxes: Name input box: <input type="text" onblur="matchUserName(true)" onkeyup="clearOther('txtUserName','txtUserID')" onkeydown="Search_OnKeyDown(event,this)" style="width: 250px; background-color: rgb(255, ...

I am experiencing an issue where components are constantly re-rendering whenever I type something. However, I would like them to

Currently, I am in the process of developing a REACT application that takes two names, calculates a percentage and then generates a poem based on that percentage. The issue I am facing is that whenever I start typing in the input fields, the LovePercentCon ...

Is there a better approach to verifying an error code in a `Response` body without relying on `clone()` in a Cloudflare proxy worker?

I am currently implementing a similar process in a Cloudflare worker const response = await fetch(...); const json = await response.clone().json<any>(); if (json.errorCode) { console.log(json.errorCode, json.message); return new Response('An ...

What could be the issue with my JSON data stream?

Trying to set up the Fullcalendar JQuery plugin with a JSON feed has been a bit of a challenge. The example provided with the plugin works perfectly, so it seems like there might be an issue with my own feed. Here is the output from the working example JS ...

Obtaining an address using latitudes and longitudes with React Google Maps

I created a map using the react-google-map plugin where users can drag the marker to get the latitude and longitude of a location. However, I am only able to retrieve the lat and lng values and not the address. How can I obtain the address as well? Take a ...

Is there a way to activate the mousewheel feature in order to zoom in and out on a webpage using jquery plugins like panzoom and circleslider?

Is there a way to enable mouse scroll functionality? For my project, I am using the CircleSlider.js library (more information available here) and jquery.panzoom-1.7.0. I have created a semi-circle where users can zoom in (+) and out (-) by moving a button ...

Navigate directly to a designated element in a React component without the need to scroll when clicking a link

When viewing a user's profile in React, clicking on an image currently scrolls to that specific image within the entire images page. However, I am looking to modify this behavior so that it navigates directly to the image element without any scrolling ...