D3 Bar Chart Help

I am working on the bar chart currently, and have stumbled upon a problem.

Here is the code:
d3.select('.chart').data(data.data).enter() .append("g") .append("rect") .attr("width", 20) .attr("height", 200) .text(function(d){ return d[1];});

In theory, that is supposed to append all the g elements to my chart. But my developer tools tells me otherwise. It actually gets added after the chart.

Anybody know how to fix this?


Can you post link to our CodePen or github so I can see the data set…

use ```d3.select(".chart").attr(“height”, 700).attr(“width”, 1000)`

I editted this post because I have the HTML file and JS files for review

Here is a link: https://github.com/tormundgiantsbane/D3-Bar-Chart
And I’ll give it a try


  • . SVG element needs a height and width - either add it to the HTML or add an attr in the jsfile

var svg = d3.select(".chart").attr("width", 1200).atttr("height", 400)

  • before append the “rect” you have to create it with selectAll -

this should get you started… let me know if this helps…

Also remeber that the element in the SVG - rect, circle, attributes - “height”, “width”, and coordinates

D3 Tips and Tricks v4.x
Bar Chart

Ohh ok, will definitely try that and let you know how it goes!

I find this post on join helpful, it gives you a brief explanation of how the selectAll(...).data(...).enter().append(...) sequence works. This post on nested selections might address your problem.

From what I gathered, since you’re doing all your operations from select, everything ends up pointing to the parent node of the selection, html, which is why all the g elements are outside of the body.

Off topic, but you don’t need Jquery to fetch the JSON, D3 has it’s own function d3.json(url[, callback]).

Wow thanks didn’t know about the json function… will for sure implement that! And thanks for the article.