score:5
Not sure where you're getting that output from, as the code you've provided doesn't create that output.
Snippet of your code here:
var data = [{"name": "A", "engine_size": "1.6", "cmpg": "28", "horsepower": "103", "msrp": "11690"},
{"name": "B", "engine_size": "1.6", "cmpg": "28", "horsepower": "103", "msrp": "12585"},
{"name": "C", "engine_size": "2.2", "cmpg": "26", "horsepower": "140", "msrp": "14610"},
{"name": "D", "engine_size": "2.2", "cmpg": "26", "horsepower": "140", "msrp": "14810"},
{"name": "E", "engine_size": "2.2", "cmpg": "26", "horsepower": "140", "msrp": "16385"}];
var outer_width = 330,
outer_height = 200,
margin = {top: 10, right: 10, bottom: 10, left: 10},
padding = {top: 20, right: 20, bottom: 20, left: 20},
inner_width = outer_width - margin.left - margin.right,
inner_height = outer_height - margin.top - margin.bottom,
width = inner_width - padding.left - padding.right,
height = inner_height - padding.top - padding.bottom;
var key = function(d) {
return d.name;
}
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.05);
var color = d3.scale.category20c();
var attribute_list = ['msrp', 'engine_size', 'horsepower', 'cmpg'];
var svg = {};
attribute_list.forEach(function(entry) {
svg[entry] = d3.select('.' + entry).append('svg')
.attr('width', outer_width)
.attr('height', outer_height)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
});
//d3.json('data/cars.json', function(error, data) {
x.domain(data.map(key));
xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.ticks(data.length);
attribute_list.forEach(function(entry) {
var g = svg[entry].append('g')
.attr('transform', 'translate(0, ' + margin.bottom + ')')
.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0, ' + height + ')')
.call(xAxis);
console.log(g.selectAll('line'));
var y = d3.scale.linear()
.domain([d3.min(data, function(d) { return +d[entry]; }),
d3.max(data, function(d) { return +d[entry]; })])
.range([height*0.2, height*0.8]);
var bars = svg[entry].selectAll('rect')
.data(data, key)
.enter();
bars.append('rect')
.attr('class', 'bar')
.attr('height', function(d) { return y(+d[entry]); })
.attr('width', function(d) { return x.rangeBand(); })
.attr('x', function(d, i) { return x(i); })
.attr('y', function(d) { return height-y(+d[entry]); })
.attr("fill", function(d){ return color(key(d)); });
});
//});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="msrp"></div>
<div class="engine_size"></div>
<div class="horsepower"></div>
<div class="cmpg"></div>
That is your code and it seemingly produces a single bar left aligned on each graph, and the X
axis looks to be labelled correctly. Each chart actually contains five bars, but they overlap.
Here is some corrected code:
var data = [{"name": "A", "engine_size": "1.6", "cmpg": "28", "horsepower": "103", "msrp": "11690"},
{"name": "B", "engine_size": "1.6", "cmpg": "28", "horsepower": "103", "msrp": "12585"},
{"name": "C", "engine_size": "2.2", "cmpg": "26", "horsepower": "140", "msrp": "14610"},
{"name": "D", "engine_size": "2.2", "cmpg": "26", "horsepower": "140", "msrp": "14810"},
{"name": "E", "engine_size": "2.2", "cmpg": "26", "horsepower": "140", "msrp": "16385"}];
var outer_width = 330,
outer_height = 200,
margin = {top: 10, right: 10, bottom: 10, left: 10},
padding = {top: 20, right: 20, bottom: 20, left: 20},
inner_width = outer_width - margin.left - margin.right,
inner_height = outer_height - margin.top - margin.bottom,
width = inner_width - padding.left - padding.right,
height = inner_height - padding.top - padding.bottom;
var key = function(d) {
return d.name;
}
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], 0.05);
var color = d3.scale.category20c();
var attribute_list = ['msrp', 'engine_size', 'horsepower', 'cmpg'];
var svg = {};
attribute_list.forEach(function(entry) {
svg[entry] = d3.select('.' + entry).append('svg')
.attr('width', outer_width)
.attr('height', outer_height)
.append('g')
.attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');
});
//d3.json('data/cars.json', function(error, data) {
x.domain(data.map(key));
xAxis = d3.svg.axis()
.scale(x)
.orient('bottom')
.ticks(data.length);
attribute_list.forEach(function(entry) {
var g = svg[entry].append('g')
.attr('transform', 'translate(0, ' + margin.bottom + ')')
.append('g')
.attr('class', 'axis')
.attr('transform', 'translate(0, ' + height + ')')
.call(xAxis);
console.log(g.selectAll('line'));
var y = d3.scale.linear()
.domain([d3.min(data, function(d) { return +d[entry]; }),
d3.max(data, function(d) { return +d[entry]; })])
.range([height*0.2, height*0.8]);
var bars = svg[entry].selectAll('rect')
.data(data, key)
.enter();
bars.append('rect')
.attr('class', 'bar')
.attr('height', function(d) { return y(+d[entry]); })
.attr('width', function(d) { return x.rangeBand(); })
.attr('x', function(d, i) { return x(d.name); })
.attr('y', function(d) { return height-y(+d[entry]); })
.attr("fill", function(d){ return color(key(d)); });
});
//});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="msrp"></div>
<div class="engine_size"></div>
<div class="horsepower"></div>
<div class="cmpg"></div>
You were calculating your X
position for each bar with:
.attr('x', function(d, i) { return x(i); })
I think you actually wanted to calculate your X
position for each bar with:
.attr('x', function(d, i) { return x(d.name); })
You were passing in the index, which is not a part of the domain defined for the X
scale, which will return undefined. Passing in the name means that you're passing in a value that's part of the domain so you'll get a corresponding co-ordinate back.
Source: stackoverflow.com
Related Query
- Looping through data attributes to create 4 separate bar charts... why are there "phantom" data elements being bound to the xAxis?
- How to create a d3 stacked bar chart that only iterates through columns 1 and 2 of data file?
- d3 bar chart using rangeRoundBands - why is there outer padding?
- Why are these Cubism horizon charts squished to the left?
- d3/dc.js - How to create a stacked bar chart while telling crossfilter to treat elements in an array as separate records?
- Two bar charts from same data object using D3.js
- Why are my donut charts positioned outside the container when other chart types are correctly positioned?
- d3 v4 why are there duplicate ticks on the X Axis (how to work tickValues)?
- Create a bar chart with local storage data (drawing the bars doesn't work)
- Loop over JSON data to create d3 pie charts
- Why does the NVD3.js line plus bar chart example render two charts instead of one?
- D3 bar chart where axis labels are hyperlinks from data
- how to create separate bar chart with JSON array set?
- How to load data to D3 chart from JSON when there are only tuples
- Why are my D3.js circles not being created and removed as live data is generated?
- Looping through extra data in D3 Directional Force Layout
- d3.js Why are axis and data slightly offset?
- Why are the first two text labels of my bar chart not shown?
- Why are there no ticks on my X (time) axis?
- changing height of bar charts from new data
- Why dc.js does not support labels for bar charts
- Is there a way I can get D3 to iterate through my data collection, plotting point by point?
- D3.js: Bars in Bar chart, scales are not modeling data properly
- D3 bar chart and html data attributes
- Unable to create a bar chart from json data using d3.js
- Bar Chart Part 1 D3 why does it skip data that is the same value?
- d3 to create paths based on separate array of data
- Is there any compatibility between HTML canvas and SVG or are they completely separate beasts?
- Normalized stacked bar chart plotting issue. All rect are equally divided irrespective of data
- d3 loop through local data variable to make stacked bar chart
More Query from same tag
- Getting results PromiseĀ {<pending>} after using the d3.csv async function
- Adding custom backgrounds to D3.js bar graph
- Different behaviour when using drag with array of numbers and array of objects
- D3 updating colors in co-occurence chart
- D3js: how to generate standalone SVG files? (Nodejs)
- In D3.js how do I rotate SVG's in a continous circular fashion
- d3.js Time Scale Chart, Array object values isnt rendering the chart whereas static values render the chart perfectly
- Getting d3.events as null in angular2 typescript code
- d3 change bar chart color according to height
- Selecting from SVG with node as argument throws DOM Exception 12
- Why is there whitespace / "overlap" between rect elements where there shouldn't be?
- D3 with Topojson only renders parts of the map
- Leaflet: How to get pixel position of a lat lng after zoom, before zoom begins
- Use superscript in d3
- d3.js can't change outer radius of arc
- Dragging a globe in D3
- Creating X-Axis with Array of Date() Objects - D3.js
- Show array values in D3.js html tooltip
- D3JS blink link
- How to set ticks for yAxis using a logarithmic (Symlog) scale?
- Is there a way to change C3 legend item tiles to be icons?
- Call the same $http.get() in 2 different directives using AngularJS
- D3.js scrolling bar chart
- Responsive d3 Funnel
- Error: value of <"rect"> = "NaN", Error:Value of <"text"> = "Nan"
- Dictate colors via column in rawgraph/d3
- Remove empty groups from dc.js graph
- D3 Pie Chart Update, IV in while loop not working well - why?
- Apply class to specific data in CSV file
- D3 force diagram - how to trigger event when nodes stop repositioning