Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9071097
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T17:49:57+00:00 2026-06-16T17:49:57+00:00

I’m trying out d3js and I have a problem with getting my first basic

  • 0

I’m trying out d3js and I have a problem with getting my first basic column(vertical bar) chart work. The only thing I find a bit difficult to understand is the scaling thing. I want to make the x and y axis ticks with labels but I have the following problems:

First of all here is my data:

{
"regions":
["Federal","Tigray","Afar","Amhara","Oromia","Gambella","Addis Ababa","Dire Dawa","Harar","Benishangul-Gumuz","Somali","SNNPR "],
"institutions":
[0,0,34,421,738,0,218,22,22,109,0,456]
}
  1. On the y-axis the values are there but the order is reversed. Here is the code:

    var y = d3.scale.linear().domain([0, d3.max(data.institutions)]).range([0, height]);

then I use this scale to create a y-axis:

var yAxis = d3.svg.axis().scale(y).orient("left");

and add this axis to the svg element

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

the problem here is that the y-axis start from 0 at the top and with 700 at the bottom which is OK but it should be in reverse order.

The other problem I have it the x-axis. I want to have an ordinal scale since the values I want to put are in the regions names I have above. So here’s what I’ve done.

var x = d3.scale.ordinal()
                    .domain(data.regions.map(function(d) { return d.substring(0, 2); }))
                    .rangeRoundBands([0, width], .1);

then the axis

var xAxis = d3.svg.axis()
                      .scale(x)
                      .orient("bottom");

and finally add it to the svg element

svgContainer.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate( 0," + height + ")")
            .call(xAxis);

Here the problem is the ticks as well as the labels appear but they are not spaced out evenly and do not correspond with the center of the rectangles I’m drawing. Here is the complete code so you can see what’s happening.

$(document).ready(function(){

    d3.json("institutions.json", draw);

});

function draw(data){
    var margin = {"top": 10, "right": 10, "bottom": 30, "left": 50}, width = 700, height = 300;

    var x = d3.scale.ordinal()
                    .domain(data.regions.map(function(d) { return d.substring(0, 2); }))
                    .rangeRoundBands([0, width], .1);


    var y = d3.scale.linear()
              .domain([0, d3.max(data.institutions)])
              .range([0, height]);

    var xAxis = d3.svg.axis()
                      .scale(x)
                      .orient("bottom");    

    var yAxis = d3.svg.axis()
                      .scale(y)
                      .orient("left");  

    var svgContainer = d3.select("div.container").append("svg")
                           .attr("class", "chart")
                           .attr("width", width + margin.left + margin.right)
                           .attr("height", height + margin.top + margin.bottom)
                          .append("g")
                            .attr("transform", "translate(" +margin.left+ "," +margin.right+ ")");        

    svgContainer.append("g")
            .attr("class", "x axis")
            .attr("transform", "translate( 0," + height + ")")
            .call(xAxis);

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

    svgContainer.selectAll(".bar")
      .data(data.institutions)
      .enter()
        .append("rect")
        .attr("class", "bar")
        .attr("x", function(d, i) {return i* 41;})
        .attr("y", function(d){return height - y(d);})
        .attr("width", x.rangeBand())
        .attr("height", function(d){return y(d);});

}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T17:49:58+00:00Added an answer on June 16, 2026 at 5:49 pm

    I put the code to Fiddle: http://jsfiddle.net/GmhCr/4/

    Feel free to edit it! I already fixed both problems.


    To fix the upside-down y-axis just swap the values of the range function arguments:

    var y = d3.scale.linear().domain([0, d3.max(data.institutions)]).range([height, 0]);
    

    Do not forget to adjust the code for the bars if you change the scale!


    The source of the mismatch between bars and the x-axis can be found here:

    var x = d3.scale.ordinal()
        .domain(data.regions.map(function(d) {
            return d.substring(0, 2);}))
        .rangeRoundBands([0, width], .1);
    
    svgContainer.selectAll(".bar")
      .data(data.institutions)
      .enter()
        .append("rect")
        .attr("class", "bar")
        .attr("x", function(d, i) {return i* 41;})
        .attr("y", function(d){return height - y(d);})
        .attr("width", x.rangeBand())
        .attr("height", function(d){return y(d);});
    

    You specify the padding for rangeRoundBands at 0.1 but you ignore the padding when computing the x and width values for the bars. This for example is correct with a padding of 0:

    var x = d3.scale.ordinal()
        .domain(data.regions.map(function(d) {
            return d.substring(0, 2);}))
        .rangeRoundBands([0, width], 0);
    
    svgContainer.selectAll(".bar").data(data.institutions).enter().append("rect")
        .attr("class", "bar")
        .attr("x", function(d, i) {
            return i * x.rangeBand();
        })
        .attr("y", function(d) {
            return y(d);
        })
        .attr("width", function(){
            return x.rangeBand();
        })
        .attr("height", function(d) {
            return height -y(d);
        });
    

    The padding determines how much of the domain is reserved for padding. When using a width of 700 and a padding of 0.1 exactly 70 pixels are used for padding. This means you have to add 70 / data[“regions”].length pixels to every bar’s x value to make this work with a padding.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I'm trying to convert HTML to plain text. I get many &\#8217; &\#8220; etc.
I have been unable to fix a problem with Java Unicode and encoding. The
I am trying to loop through a bunch of documents I have to put
I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
I am trying to understand how to use SyndicationItem to display feed which is
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.