I am looking for an algorithm for my hobby task.
For example we have test data cases:
var case1 = ['green', 'red', 'red', 'blue', 'green', 'green', 'green'];
var case2 = ['blue', 'blue', 'green', 'yellow', 'blue', 'orange', 'green', 'green', 'green', 'green'];
var case3 = ['purple', 'blue', 'blue', 'blue', 'red'];
Output:
var result1 = ['red', 'red', 'green', 'green', 'green'];
var result2 = ['blue', 'blue', 'green', 'green', 'green', 'green'];
var result3 = ['blue', 'blue', 'blue'];
Can anybody tell me which algorithm I should use? The classic way with duplicates - not like I looking.
Short version
we can use the .filter function to achieve this behavior.
.filter((item, i, array) => array[i - 1] == item || item == array[i + 1])
let case1 = ['green', 'red', 'red', 'blue', 'green', 'green', 'green'];
let case2 = ['blue', 'blue', 'green', 'yellow', 'blue', 'orange', 'green', 'green', 'green', 'green'];
let case3 = ['purple', 'blue', 'blue', 'blue', 'red'];
let result1 = case1.filter((item, i, array) => array[i - 1] == item || item == array[i + 1])
let result2 = case2.filter((item, i, array) => array[i - 1] == item || item == array[i + 1])
let result3 = case3.filter((item, i, array) => array[i - 1] == item || item == array[i + 1])
console.log(result1)
console.log(result2)
console.log(result3)
out of bounds index in javascript will return undefined which will evaluate to false in your comparison
So in javascript a naive implementation would be:
function selectSequential(source) {
var result = [];
for (let i = 0; i < source.length; i++) {
if ((i != source.length-1 && source[i+1] === source[i])
|| (i != 0 && source[i-1] === source[i])) {
result.push(source[i]);
}
}
return result;
}
Related
Is there a way to limit the brushing height - say 50% of y axis (only from Y axis 0 - 250, brushing should work) ? Example fiddle
JS Code:
var hitslineChart = dc.barChart("#chart-line-hitsperday");
var data = [
{date: "12/27/2012", http_404: 2, http_200: 190, http_302: 100},
{date: "12/28/2012", http_404: 2, http_200: 10, http_302: 100},
{date: "12/29/2012", http_404: 1, http_200: 300, http_302: 200},
{date: "12/30/2012", http_404: 2, http_200: 90, http_302: 0},
{date: "12/31/2012", http_404: 2, http_200: 90, http_302: 0},
{date: "01/01/2013", http_404: 2, http_200: 90, http_302: 0},
{date: "01/02/2013", http_404: 1, http_200: 10, http_302: 1},
{date: "01/03/2013", http_404: 2, http_200: 90, http_302: 0},
{date: "01/04/2013", http_404: 2, http_200: 90, http_302: 0},
{date: "01/05/2013", http_404: 2, http_200: 90, http_302: 0},
{date: "01/06/2013", http_404: 2, http_200: 200, http_302: 1},
{date: "01/07/2013", http_404: 1, http_200: 200, http_302: 100}
];
var ndx = crossfilter(data);
var parseDate = d3.time.format("%m/%d/%Y").parse;
data.forEach(function(d) {
d.date = Date.parse(d.date);
d.total= d.http_404+d.http_200+d.http_302;
});
var dateDim = ndx.dimension(function(d) {return d.date;});
var hits = dateDim.group().reduceSum(function(d) {return d.total;});
var minDate = dateDim.bottom(1)[0].date;
var maxDate = dateDim.top(1)[0].date;
hitslineChart.width(500)
.height(200)
.dimension(dateDim)
.group(hits)
.x(d3.time.scale().domain([minDate,maxDate]));
dc.renderAll();
Thanks,
Arun
Although your example uses dc.js 1.7.0, I'm going to answer for dc.js 2.0, since it's a lot newer and a few APIs have changed.
The technique is to override the functions from the coordinateGridMixin which size the brush. This gets a little hairy, but it's possible.
It turns out we'll have to override three undocumented functions which render the brush, renderBrush, setBrushY, and (unfortunately) resizeHandlePath.
The reason this gets hairy is that we really want to override brushHeight, but that one is a private function.
We'll define our own like this:
function height_over_2() {
return (hitslineChart._xAxisY() - hitslineChart.margins().top)/2;
}
For renderBrush, we need to shift the brush down by height_over_2(). We'll pass through the call first, then modify the transform:
dc.override(hitslineChart, 'renderBrush', function(g) {
hitslineChart._renderBrush(g);
var gBrush = hitslineChart.select('g.brush')
.attr('transform', 'translate(' + hitslineChart.margins().left + ',' + (hitslineChart.margins().top + height_over_2()) + ')')
});
setBrushY we'll replace entirely (we could just assign to it, but we'll use dc.override for consistency):
dc.override(hitslineChart, 'setBrushY', function(gBrush) {
gBrush.selectAll('rect')
.attr('height', height_over_2());
gBrush.selectAll('.resize path')
.attr('d', hitslineChart.resizeHandlePath);
});
Finally, resizeHandlePath also uses the height, and here we (ugh) have to copy a big chunk of code out of dc.js, which was itself copied from the crossfilter demo:
dc.override(hitslineChart, 'resizeHandlePath', function (d) {
var e = +(d === 'e'), x = e ? 1 : -1, y = height_over_2() / 3;
return 'M' + (0.5 * x) + ',' + y +
'A6,6 0 0 ' + e + ' ' + (6.5 * x) + ',' + (y + 6) +
'V' + (2 * y - 6) +
'A6,6 0 0 ' + e + ' ' + (0.5 * x) + ',' + (2 * y) +
'Z' +
'M' + (2.5 * x) + ',' + (y + 8) +
'V' + (2 * y - 8) +
'M' + (4.5 * x) + ',' + (y + 8) +
'V' + (2 * y - 8);
});
Fork of your fiddle: http://jsfiddle.net/gordonwoodhull/anz9gfy0/13/
I want to visualize state changes over time, and I'm not sure how to do it using d3 transitions. Simple chained transitions are pretty straightforward. But in this case, for each transition I need access to the object's data and I also need a way to keep track of the count of the transition I'm currently on (so I know which state change to use).
It's easy to do a simple brute force version:
http://bl.ocks.org/aschneiderman/4f7a8824c96f33aa7ad48c729b739409
var members = [
{ id: 1, state: [1, 3, 1, 2, 3] },
{ id: 2, state: [1, 2, 2, 1, 1] },
{ id: 7, state: [2, 3, 1, 2, 3] },
{ id: 112, state: [2, 2, 2, 1, 3] },
{ id: 127, state: [3, 3, 1, 2, 1] },
[...]
{ id: 296, state: [2, 1, 1, 2, 1] }
];
var Distance = 200;
d3.select("svg").selectAll("rect")
.data(members)
.enter().append("rect")
.attr("x",0)
.attr("y",function(d,i) { return 80 + ( 500 - ((d.state[0] % 3) * 250) ) + i*25} )
.attr("width",10)
.attr("height",10)
.style("fill", "Crimson")
.transition()
.ease(d3.easeLinear)
.duration(600)
.delay(0)
.attr("x", 60 + (1 * Distance))
.attr("y", function(d,i) { return 80 + ( 500 - ((d.state[1] % 3) * 250) ) + i*25} )
.transition()
.ease(d3.easeLinear)
.duration(600)
.delay(0)
.attr("x", 60 + (2 * Distance))
.attr("y", function(d,i) { return 80 + ( 500 - ((d.state[2] % 3) * 250) ) + i*25} )
.transition()
.ease(d3.easeLinear)
.duration(600)
.delay(0)
.attr("x", 60 + (3 * Distance))
.attr("y", function(d,i) { return 80 + ( 500 - ((d.state[3] % 3) * 250) ) + i*25} ) ;
How do I modify the code so I can run n transitions on each rectangle, where n = the number of state changes? Any pointers or d3 examples would be greatly appreciated.
In LineBar.json
[
{
"key" : "Data09" ,
"bar": true,
"color": "#ccf",
"values": [[1469440800000, 0]
, [1469444400000, 0]
, [1469444400000, 3]
, [1469448000000, 0]
, [1469451600000, 0]
, [1469451600000, 3]
, [1469455200000, 0]
, [1469455200000, 5]
, [1469458800000, 9]
]
} ,
{
"key" : "Data34" ,
"color" : "#333",
"values" : [[1469440800000, 0], [1469441400000, 0], [1469441400000, 2]
, [1469442000000, 0], [1469442600000, 0], [1469443200000, 0]
, [1469443800000, 0], [1469444400000, 0], [1469444400000, 1]
, [1469445000000, 0], [1469445600000, 0], [1469446200000, 0]
, [1469446800000, 0], [1469447400000, 0], [1469448000000, 0]
, [1469448600000, 0], [1469448600000, 1], [1469449200000, 0]
, [1469449800000, 0], [1469449800000, 1], [1469450400000, 0]
, [1469450400000, 1], [1469451000000, 0], [1469451600000, 0]
, [1469452200000, 0], [1469452800000, 0], [1469453400000, 0]
, [1469453400000, 1], [1469454000000, 0], [1469454600000, 0]
, [1469454600000, 3], [1469455200000, 0], [1469455200000, 1], [1469455800000, 0]]
}
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.2/d3.min.js" charset="utf-8"></script>
<script src="../build/nv.d3.js"></script>
<script>
var chart;
d3.json( "lineBar.json", function ( error, data )
{
nv.addGraph( function ()
{
var chart = nv.models.linePlusBarChart()
.margin( { top: 30, right: 60, bottom: 50, left: 70 } )
//We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
.x( function ( d, i ) { return i } )
.y( function ( d, i ) { return d[1]; } )
;
chart.xAxis.tickFormat( function ( d )
{
//alert( d + ', ' + data[0].values[d][0] );
var dx = data[0].values[d] && data[0].values[d][0] || 0;
//alert( d + ', ' + dx );
return d3.time.format( '%m/%d %H.%M' )( new Date( dx ) )
} );
chart.y1Axis
.tickFormat( d3.format( ',f' ) );
chart.y2Axis
.tickFormat( function ( d ) { return d3.format( ',f' )( d ) } );
chart.bars.forceY( [0] );
d3.select( '#chart1 svg' )
.datum( data )
.transition()
.duration( 0 )
.call( chart );
nv.utils.windowResize( chart.update );
return chart;
} );
} );
</script>
When I ran it, my xAxis 's time (except the first few intervals being correct) have all had a New Year Eve's date (not knowing where that came from)! So I changed the xAxis Data Accessor from i to i/3, it "improved" but still not all right! (Fig.2)
var chart = nv.models.linePlusBarChart()
.margin( { top: 30, right: 60, bottom: 50, left: 70 } )
//We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
.x( function ( d, i ) { return i/3 } )
.y( function ( d, i ) { return d[1]; } )
;
I have been working on this tickmarks for 2 days already, so frustrating that I almost wanted to deflect from using d3! I need help!
I acquired those date numerals UTC from writing this function
function toUTC( DD )
{
var date = new Date( "2017-01-23 21:23:59.999" );
if ( DD ) date = new Date( DD );
var yyyy = date.getFullYear();
var MM = date.getMonth();
var dd = date.getDate();
var HH = date.getHours();
var mm = date.getMinutes();
var ss = date.getSeconds();
var ms = date.getMilliseconds();
var UTC = Date.UTC( yyyy, MM, dd, HH, mm, ss, ms );
return ( UTC );
};
I found the answer !! The problem that I have above is I was using the series that has lower frequency for my time ticks! I need to calc my time-ticks using intervals from the graph of higher frequency.
var chart = nv.models.linePlusBarChart()
.margin( { top: 30, right: 60, bottom: 50, left: 70 } )
//We can set x data accessor to use index. Reason? So the bars all appear evenly spaced.
.x( function ( d, i ) { return i } )
.y( function ( d, i ) { return d[1]; } )
;
chart.xAxis.tickFormat( function ( d ) {
var dx = data[1].values[d] && data[1].values[d][0] || 0;
return d3.time.format( '%m/%d %H.%M' )( new Date( dx ) )
} );
The description of the selection.data function includes an example with multiple groups (link) where a two-dimensional array is turned into an HTML table.
In d3.js v3, for lower dimensions, the accessor functions included a third argument which was the index of the parent group's datum:
td.text(function(d,i,j) {
return "Row: " + j;
});
In v4, this j argument has been replaced by the selection's NodeList. How do I access the parent group's datum index now?
Well, sometimes an answer doesn't provide a solution, because the solution may not exist. This seems to be the case.
According to Bostock:
I’ve merged the new bilevel selection implementation into master and also simplified how parents are tracked by using a parallel parents array.
A nice property of this new approach is that selection.data can
evaluate the values function in exactly the same manner as other
selection functions: the values function gets passed {d, i, nodes}
where this is the parent node, d is the parent datum, i is the parent
(group) index, and nodes is the array of parent nodes (one per group).
Also, the parents array can be reused by subselections that do not
regroup the selection, such as selection.select, since the parents
array is immutable.
This change restricts functionality—in the sense that you cannot
access the parent node from within a selection function, nor the
parent data, nor the group index — but I believe this is ultimately A
Good Thing because it encourages simpler code.
(emphasis mine)
Here's the link: https://github.com/d3/d3-selection/issues/47
So, it's not possible to get the index of the parent's group using selection (the parent's group index can be retrieved using selection.data, as this snippet bellow shows).
var testData = [
[
{x: 1, y: 40},
{x: 2, y: 43},
{x: 3, y: 12},
{x: 6, y: 23}
], [
{x: 1, y: 12},
{x: 4, y: 18},
{x: 5, y: 73},
{x: 6, y: 27}
], [
{x: 1, y: 60},
{x: 2, y: 49},
{x: 3, y: 16},
{x: 6, y: 20}
]
];
var svg = d3.select("body")
.append("svg")
.attr("width", 300)
.attr("height", 300);
var g = svg.selectAll(".groups")
.data(testData)
.enter()
.append("g");
var rects = g.selectAll("rect")
.data(function(d, i , j) { console.log("Data: " + JSON.stringify(d), "\nIndex: " + JSON.stringify(i), "\nNode: " + JSON.stringify(j)); return d})
.enter()
.append("rect");
<script src="https://d3js.org/d3.v4.min.js"></script>
My workaround is somewhat similar to Dinesh Rajan's, assuming the parent index is needed for attribute someAttr of g.nestedElt:
v3:
svg.selectAll(".someClass")
.data(nestedData)
.enter()
.append("g")
.attr("class", "someClass")
.selectAll(".nestedElt")
.data(Object)
.enter()
.append("g")
.attr("class", "nestedElt")
.attr("someAttr", function(d, i, j) {
});
v4:
svg.selectAll(".someClass")
.data(nestedData)
.enter()
.append("g")
.attr("class", "someClass")
.attr("data-index", function(d, i) { return i; }) // make parent index available from DOM
.selectAll(".nestedElt")
.data(Object)
.enter()
.append("g")
.attr("class", "nestedElt")
.attr("someAttr", function(d, i) {
var j = +this.parentNode.getAttribute("data-index");
});
I ended up defining an external variable "j" and then increment it whenever "i" is 0
example V3 snippet below.
rowcols.enter().append("rect")
.attr("x", function (d, i, j) { return CalcXPos(d, j); })
.attr("fill", function (d, i, j) { return GetColor(d, j); })
and in V4, code converted as below.
var j = -1;
rowcols.enter().append("rect")
.attr("x", function (d, i) { if (i == 0) { j++ }; return CalcXPos(d, j); })
.attr("fill", function (d, i) { return GetColor(d, j); })
If j is the nodeList...
j[i] is the current node (eg. the td element),
j[i].parentNode is the level-1 parent (eg. the row element),
j[i].parentNode.parentNode is the level-2 parent (eg. the table element),
j[i].parentNode.parentNode.childNodes is the array of level-1 parents (eg. array of row elements) including the original parent.
So the question is, what is the index of the parent (the row) with respect to it's parent (the table)?
We can find this using Array.prototype.indexOf like so...
k = Array.prototype.indexOf.call(j[i].parentNode.parentNode.childNodes,j[i].parentNode);
You can see in the snippet below that the row is printed in each td cell when k is returned.
var testData = [
[
{x: 1, y: 1},
{x: 1, y: 2},
{x: 1, y: 3},
{x: 1, y: 4}
], [
{x: 2, y: 1},
{x: 2, y: 2},
{x: 2, y: 3},
{x: 2, y: 4}
], [
{x: 3, y: 4},
{x: 3, y: 4},
{x: 3, y: 4},
{x: 3, y: 4}
]
];
var tableData =
d3.select('body').selectAll('table')
.data([testData]);
var tables =
tableData.enter()
.append('table');
var rowData =
tables.selectAll('table')
.data(function(d,i,j){
return d;
});
var rows =
rowData.enter()
.append('tr');
var eleData =
rows.selectAll('tr')
.data(function(d,i,j){
return d;
});
var ele =
eleData.enter()
.append('td')
.text(function(d,i,j){
var k = Array.prototype.indexOf.call(j[i].parentNode.parentNode.childNodes,j[i].parentNode);
return k;
});
<script src="https://d3js.org/d3.v4.min.js"></script>
Reservations
This approach is using DOM order as a proxy for data index. In many cases, I think this is a viable band-aid solution if this is no longer possible in D3 (as reported in this answer).
Some extra effort in manipulating the DOM selection to match data might be needed. As an example, filtering j[i].parentNode.parentNode.childNodes for <tr> elements only in order to determine the row -- generally speaking the childNodes array may not match the selection and could contain extra elements/junk.
While this is not a cure-all, I think it should work or could be made to work in most cases, presuming there is some logical connection between DOM and data that can be leveraged which allows you to use DOM child index as a proxy for data index.
Here's an example of how to use the selection.each() method. I don't think it's messy, but it did slow down the render on a large matrix. Note the following code assumes an existing table selection and a call to update().
update(matrix) {
var self = this;
var tr = table.selectAll("tr").data(matrix);
tr.exit().remove();
tr.enter().append("tr");
tr.each(addCells);
function addCells(data, rowIndex) {
var td = d3.select(this).selectAll("td")
.data(function (d) {
return d;
});
td.exit().remove();
td.enter().append("td");
td.attr("class", function (d) {
return d === 0 ? "dead" : "alive";
});
td.on("click", function(d,i){
matrix[rowIndex][i] = d === 1 ? 0 : 1; // rowIndex now available for use in callback.
});
}
setTimeout(function() {
update(getNewMatrix(matrix))
}, 1000);
},
Assume you want to do a nested selectiom, and your
data is some array where each element in turn
contains an array, let's say "values". Then you
have probably some code like this:
var aInnerSelection = oSelection.selectAll(".someClass") //
.data(d.values) //
...
You can replace the array with the values by a new array, where
you cache the indices within the group.
var aInnerSelection = oSelection.selectAll(".someClass") //
.data(function (d, i) {
var aData = d.values.map(function mapValuesToIndexedValues(elem, index) {
return {
outerIndex: i,
innerIndex: index,
datum: elem
};
})
return aData;
}, function (d, i) {
return d.innerIndex;
}) //
...
Assume your outer array looks like this:
[{name "X", values: ["A", "B"]}, {name "y", values: ["C", "D"]}
With the first approach, the nested selection brings you from here
d i
------------------------------------------------------------------
root dummy X {name "X", values: ["A", "B"]} 0
dummy Y {name "Y", values: ["C", "D"]} 1
to here.
d i
------------------------------------------------------------------
root X A "A" 0
B "B" 1
Y C "C" 2
D "D" 3
With the augmented array, you end up here instead:
d i
------------------------------------------------------------------
root X A {datum: "A", outerIndex: 0, innerIndex: 0} 0
B {datum: "B", outerIndex: 0, innerIndex: 1} 1
Y C {datum: "C", outerIndex: 1, innerIndex: 0} 2
D {datum: "D", outerIndex: 1, innerIndex: 1} 3
So you have within the nested selections, in any function(d,i), all
information you need.
Here's a snippet I crafter after re-remembering this usage of .each for nesting, I thought it may be useful to others who end up here. This examples creates two layers of circles, and the parent group index is used to determine the color of the circles - white for the circles in the first layer, and black for the circles in the top layer (only two layers in this case).
const nested = nest().key(layerValue).entries(data);
let layerGroups = g.selectAll('g.layer').data(nested);
layerGroups = layerGroups.enter().append('g').attr('class', 'layer')
.merge(layerGroups);
layerGroups.each(function(layerEntry, j) {
const circles = select(this)
.selectAll('circle').data(layerEntry.values);
circles.enter().append('circle')
.merge(circles)
.attr('cx', d => xScale(xValue(d)))
.attr('cy', d => yScale(yValue(d)))
.attr('r', d => radiusScale(radiusValue(d)))
.attr('fill', j === 0 ? 'white' : 'black'); // <---- Access parent index.
});
My solution was to embed this information in the data provided to d3js
data = [[1,2,3],[4,5,6],[7,8,9]]
flattened_data = data.reduce((acc, v, i) => {
v.forEach((d, j) => {
data_item = { i, j, d };
acc.push(data_item);
});
return acc;
}, []);
Then you can access i, j and d from the data arg of the function
td.text(function(d) {
// Can access i, j and original data here
return "Row: " + d.j;
});
Given I have 3 arrays that are mapped to each other.
fruit = ['apple', 'avocado', 'banana']
color = ['red', 'purple', 'yellow']
price = [30, 20, 50]
How do create an array of hashes with the following value
[
{fruit: 'apple', color: 'red', price: 30},
{fruit: 'avocado', color: 'purple', price: 20},
{fruit: 'banana', color: 'yellow', price: 50}
]
You can use zip to interleave the arrays, and then map them into an array of hashes:
fruit.zip(color, price).map { |f, c, p| { fruit: f, color: c, price: p } }
# => [{:fruit=>"apple", :color=>"red", :price=>30},
# => {:fruit=>"avocado", :color=>"purple", :price=>20},
# => {:fruit=>"banana", :color=>"yellow", :price=>50}
# => ]