d3js: ordinal scale with not unique labels [duplicate] - d3.js

I'm new to d3 and using it for creating a simple chart using array of numbers where the value '16' appears twice in it.
It generate the chart with one 'missing' 'rect' element for the 2nd '16' value, when I check the html I see that both '16' rect has same 'y' value of 72.
Please tell me what I'm doing wrong, thanks
code:
var data = [4, 8, 15, 16, 23, 16];
var chart = d3.select("body").append("svg")
.attr("class", "chart")
.attr("width", 420)
.attr("height", 20 * data.length);
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420])
var y = d3.scale.ordinal()
.domain(data)
.rangeBands([0, 120]);
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("y", y)
.attr("width", x)
.attr("height", y.rangeBand());

The problem with your code is that you are trying to use the values from your data array to create range bands on an ordinal scale. Since the same input value will always be mapped to the same output value that means that both inputs 16 get mapped to the same range band 72.
If you want each input value to be mapped to its own "bar" then you need to use array indices instead of array values.
First you prepare the indices
var indices = d3.range(0, data.length); // [0, 1, 2, ..., data.length-1]
Then you use them to define the y scale domain
var y = d3.scale.ordinal()
.domain(indices)
// use rangeRoundBands instead of rangeBands when your output units
// are pixels (or integers) if you want to avoid empty line artifacts
.rangeRoundBands([0, chartHeight]);
Finally, instead of using array values as inputs use array indices when mapping to y
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("y", function (value, index) {
// use the index as input instead of value; y(index) instead of y(value)
return y(index);
})
.attr("width", x)
.attr("height", y.rangeBand());
As an added bonus this code will automatically rescale the chart if the amount of data changes or if you decide to change the chart width or height.
Here's a jsFiddle demo: http://jsfiddle.net/q8SBN/1/
Complete code:
var data = [4, 8, 15, 16, 23, 16];
var indices = d3.range(0, data.length);
var chartWidth = 420;
var chartHeight = 120;
var chart = d3.select("body").append("svg")
.attr("class", "chart")
.attr("width", chartWidth)
.attr("height", chartHeight);
var x = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, chartWidth])
var y = d3.scale.ordinal()
.domain(indices)
.rangeRoundBands([0, chartHeight]);
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("y", function (value, index) { return y(index); })
.attr("width", x)
.attr("height", y.rangeBand());

The way you are setting the y attribute of the rectangles will utilize the same value for all duplicate elements. You can use some offsetting like so:
chart.selectAll("rect")
.data(data)
.enter().append("rect")
.attr("y", function (d, i) {
return (i * y.rangeBand()) + y.rangeBand();})
.attr("width", x)
.attr("height", y.rangeBand());
Also you might have to adjust the height of your overall chart to see all the bands.

Related

How to control the spacings of the x Axis label positions in a stacked bar chart?

I took bits from this and this solutions.
I then do the following to show my x axis label ticks:
var x = d3.scaleBand().range([0, width]).padding(.1).domain(d3.range(1993, 2002));
svg.append("g")
.attr('class', 'axis')
.attr('transform', 'translate(-10,' + (height - 20) + ')')
.call(d3.axisBottom(x));
However, I then get the following output where x axis ticks are shifted further to the right each time like if their gap doesn't match the bar's.
The following snippet shows how the rects and axis's ticks line up correctly.
Need to be careful on how d3.range generates arrays, in that d3.range(1993, 2002) will create [1993, 1994, ... , 2001].
Also, I'm not sure why the g element that contains the X axis was shifted left, so that is set to 0
var width = 800
var height = 100
//this makes an array 1993 to 2001. Is that what you want?
var data = d3.range(1993, 2002)
var x = d3.scaleBand()
.range([0, width])
.padding(.1)
.domain(data);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
svg.append("g")
.attr('class', 'axis')
//.attr('transform', 'translate(-10,' + (height - 20) + ')')
.attr('transform', 'translate(0,' + (height - 20) + ')')
.call(d3.axisBottom(x));
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('x', d => x(d))
.attr('y', 0)
.attr('width', x.bandwidth())
.attr('height', x.bandwidth())
<script src="https://d3js.org/d3.v4.min.js"></script>
I don't have enough S.O to 'comment' but I think it may be helpful to use the xScale:
-in the xAxis (something like...
xAxis = d3.axisBottom()
.scale(xScale)
)
-in the x position of each bar ( something like...
'x', d => xScale(year)
)
-in the width of each bar, seems like you might need to use something like...
('width', x.bandwidth())
looks like the xScale in the (1)axis and (2)bars are not working as expected together.
Maybe this helps?!

D3 v4 - make a horizontal bar chart with fixed width

I have made a horizontal bar chart using d3 v4, which works fine except for one thing. I am not able to make the bar height fixed. I am using bandwidth() currently and if i replace it with a fixed value say (15) the problem is that it does not align with the y axis label/tick http://jsbin.com/gigesi/3/edit?html,css,js,output
var w = 200;
var h = 400;
var svg = d3.select("body").append("svg")
.attr("width", w)
.attr("height", h)
.attr("transform", "translate(80,30)");
var data = [
{Item: "Item 1", count: "11"},
{Item: "Item 2", count: "14"},
{Item: "Item 3", count: "10"},
{Item: "Item 4", count: "14"}
];
var xScale = d3.scaleLinear()
.rangeRound([0,w])
.domain([0, d3.max(data, function(d) {
return d.count;
})]);
var yScale = d3.scaleBand()
.rangeRound([h,0]).padding(0.2)
.domain(data.map(function(d) {
return d.Item;
}));
var yAxis = d3.axisLeft(yScale);
svg.append('g')
.attr('class','axis')
.call(yAxis);
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('width', function(d,i) {
return xScale(d.count);
})
.attr('height', yScale.bandwidth())
.attr('y', function(d, i) {
return yScale(d.Item);
}).attr("fill","#000");
The y axis seemed to be off SVG in the link you provided. (Maybe you have overflow: visible; for the SVG.
Anyway, I've added a few margins to the chart so that the whole chart is visible. Here it is (ignore the link description):
DEMO: H BAR CHART WITH HEIGHT POSITIONING TO THE TICKS
Relevant code changes:
As you are using a scale band, the height is computed within. You just need to use .bandWidth().
.attr('height', yScale.bandwidth())
Added a margin and transformed the axis and the bars to make the whole chart visible :
: I'm assigning margins so that the y-axis is within the viewport of the SVG which makes it easier to adjust the left margin based on the tick value as well. And I think this should be a standard practice.
Also, if you notice, the rects i.e. bars are now a part of <g class="bars"></g>. Inspect the DOM if you'd like. This would be useful for complex charts with a LOT of elements but it's always a good practice.
var margin = {top: 10, left: 40, right: 30, bottom: 10};
var xScale = d3.scaleLinear()
.rangeRound([0,w-margin.left-margin.right])
var yScale = d3.scaleBand()
.rangeRound([h-margin.top-margin.bottom,0]).padding(0.2)
svg.append('g')
.attr('class','axis')
.attr('transform', 'translate(' + margin.left+', '+margin.top+')')
Try changing the data and the bar height will adjust and align according to the ticks. Hope this helps. Let me know if you have any questions.
EDIT:
Initially, I thought you were facing a problem placing the bars at the center of the y tick but as you said you needed fixed height bars, here's a quick addition to the above code that lets you do that. I'll add another approach using the padding (inner and outer) sometime soon.
Updated JS BIN
To position the bar exactly at the position of the axis tick, I'm moving the bar from top to the scale's bandwidth that is calculated by .bandWidth() which will the position it starting right from the tick and now subtracting half of the desired height half from it so that the center of the bar matches the tick y. Hope this explains.
.attr('height', 15)
.attr('transform', 'translate(0, '+(yScale.bandwidth()/2-7.5)+')')

Scale padding in D3 v 4

How to make non-padding edge of the x-scale? There is .rangeBand() in v3, but I am using D3 v4.
var x = d3.scaleBand().rangeRound([0, width], .05).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
Short answer:
You can't anymore.
Long answer:
In D3 v4.x there is a paddingOuter method for band scales:
band.paddingOuter([padding]):
If padding is specified, sets the outer padding to the specified value which must be in the range [0, 1]. If padding is not specified, returns the current outer padding which defaults to 0. The outer padding determines the ratio of the range that is reserved for blank space before the first band and after the last band. (emphasis mine)
However, as you can see, that value goes only from 0 to 1.
Here is a demo with zero outer padding:
var w = 500, h = 100;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var scale = d3.scaleBand()
.domain("ABCDEFGHIJKL".split(""))
.range([20, w - 20])
.paddingOuter(0)
var axis = d3.axisBottom(scale);
var gX = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis)
<script src="https://d3js.org/d3.v4.min.js"></script>
And here is another with the maximum (1) outer padding:
var w = 500, h = 100;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var scale = d3.scaleBand()
.domain("ABCDEFGHIJKL".split(""))
.range([20, w - 20])
.paddingOuter(1)
var axis = d3.axisBottom(scale);
var gX = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis)
<script src="https://d3js.org/d3.v4.min.js"></script>
There is an open issue on GitHub, asking for unlimited outer padding, with a comment from Mike Bostock (D3 creator) in the pull request.
Possible solutions
Of course, you can download D3 v4 and tweak the band scale function, creating your own function, nothing forbids you. If you want to follow that approach, have a look at the pull request linked above, it just removes Math.min(1, _) from the source code.
A way easier solution is this hacky one below: create fake values at the beginning and end of your domain...
.domain(["foo", "bar", "baz"].concat(domain).concat(["foobar", "foobaz", "barbaz"]))
... and ignore them in the axis:
var axis = d3.axisBottom(scale)
.tickValues(domain);
Here is the demo:
var w = 500, h = 100;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var domain = "ABCDEFGHIJKL".split("")
var scale = d3.scaleBand()
.domain(["foo", "bar", "baz"].concat(domain).concat(["foobar", "foobaz", "barbaz"]))
.range([20, w - 20]);
var axis = d3.axisBottom(scale)
.tickValues(domain);
var gX = svg.append("g")
.attr("transform", "translate(0,50)")
.call(axis)
<script src="https://d3js.org/d3.v4.min.js"></script>

d3 donut/pie chart - drawing a line between arcs

can't figure to find the endpoint of the arc to draw a line from (0,0) to the arc's endpoint..image attached
I could find the centroid of the arc and draw a line but here I want to pull a line to end of arc so that I can extend that line to the left /right side (and then append the circle at line's endpoint)...could't find any such solution over whole google. Any help will be appreciated. Just a hint will do.
When you pass a data array to the pie generator, it returns an array of objects with the following properties:
data - the input datum; the corresponding element in the input data array.
value - the numeric value of the arc.
index - the zero-based sorted index of the arc.
startAngle - the start angle of the arc.
endAngle - the end angle of the arc.
padAngle - the pad angle of the arc.
From these, you can use startAngle or endAngle to draw your lines, since they hold the arcs' starting points (and endpoints).
But there is a catch: unlike the regular trigonometric representation, D3 pie generator puts the 0 angle at 12 o'clock:
The angular units are arbitrary, but if you plan to use the pie generator in conjunction with an arc generator, you should specify angles in radians, with 0 at -y (12 o’clock) and positive angles proceeding clockwise.
Therefore, we have to subtract Math.PI/2 to get the correct angles.
In the following demo, the coordinates are calculates using sine and cosine:
.attr("y2", function(d) {
return Math.sin(d.startAngle - Math.PI / 2) * (outerRadius)
})
.attr("x2", function(d) {
return Math.cos(d.startAngle - Math.PI / 2) * (outerRadius)
})
Check the demo:
var data = [10, ,12, 50, 15, 20, 40, 6, 32, 17];
var width = 500,
height = 400,
radius = Math.min(width, height) / 2;
var color = d3.scaleOrdinal(d3.schemeCategory10)
var pie = d3.pie()
.sort(null);
var arc = d3.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 50);
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll(null)
.data(pie(data))
.enter().append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
var lines = svg.selectAll(null)
.data(pie(data))
.enter()
.append("line")
.attr("x1", 0)
.attr("y1", 0)
.attr("y2", function(d) {
return Math.sin(d.startAngle - Math.PI / 2) * (radius - 50)
})
.attr("x2", function(d) {
return Math.cos(d.startAngle - Math.PI / 2) * (radius - 50)
})
.attr("stroke", "black")
.attr("stroke-width", 1)
<script src="https://d3js.org/d3.v4.min.js"></script>
Once you apply pie layout to your dataset by doing
var pieData = myPieLayout(myDataset)
inside pieData you will find, for each element of your dataset, two properties called startAngle and endAngle. Using that, you can find the position of the point you want, from the center of the pie by iterating through pieData elements and doing
var x = Math.cos(d.endAngle)*radius
var y = Math.sin(d.endAngle)*radius

D3.js ignores duplicate values

I'm exploring D3.js. I primarily used their tutorial to get what I have. But I have made some adjustments.
What I'm doing is counting the number of active & inactive items in a specific table. It then displays a graph with those values. Most everything works fines. I have 2 issues with it though:
It doesn't update automatically with my AJAX call when items are deleted. Only updates when items are added. But I'm not concerned about this for this post.
My primary issue: duplicate values aren't being treated as individual numbers. Instead it sees [10,10] and outputs it as a single bar in the graph as 10 (instead of 2 bars).
Looking at the D3 docs, it would seem the issue lies with .data. Documentation mentions that it joins data.
$(document).on("DOMSubtreeModified DOMNodeRemoved", ".newsfeed", function() {
var columns = ['created','deleted'];
var data = [numN, numD];
var y = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, 420]);
var x = d3.scale.ordinal()
.domain(columns)
.rangeBands([0, 120]);
chart.selectAll("rect")
.data(data)
//.enter().append("rect")
.attr("x", x)
.attr("height", y)
.attr("width", x.rangeBand())
.attr("rx", 10)
.attr("ry", 10);
chart.selectAll("text")
.data(data)
//.enter().append("text")
.attr("y", y)
.attr("x", function(d) {
return x(d) + x.rangeBand() / 2;
}) //offset
.attr("dy", -10) // padding-right
.attr("dx", ".35em") // vertical-align: middle
.attr("text-anchor", "end") // text-align: right
.text(String);
});
How can I make each value to display? If I pass in two different values, the chart displays as it should.
Your problem is at .attr("x", x). So the way you're doing it assigns the same x coordinate for both rects.
So try offsetting x coordinate.
.attr("x", function(d, i) { x + i * width_of_your_rect); })

Resources