Related
I am exploring ways to illustrate a directional walking route via animating dots (that are all smoothly moving in 1 direction) and I wanted to see if there is anything that I am missing. I am running into a similar issue in "#react-native-mapbox-gl/maps": "8.5.0" with MapboxGL.LineLayer and then updating style.lineDasharray via setInterval to simulate an animation. The issue also seem to persist in mapbox-gl-js/v0.34.
It appears that the animation looks correct when using lineCap: 'butt', but it breaks down when I switch to lineCap: 'round'. Even when it works correctly, you can see a 1 pixel static lines with line-cap: "butt". I assume it's it looks broken when we switch to "round" because the library code attempts to create a round shape and adds left & right pieces. Basically, it looks like some dashes are moving and some are static (see attached videos). Any tricks to make this into a smooth mono-directional animation? Here is a code snippet that demonstrates the issue.
https://codepen.io/prototypersf/pen/XWYwBYN?editors=1010
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title></title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.34.0/mapbox-gl.js'></script>
<link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.34.0/mapbox-gl.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<div id='map'></div>
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibHVjYXN3b2oiLCJhIjoiY2l5Nmg4cWU1MDA0ejMzcDJtNHJmZzJkcyJ9.WhcEdTYQH6sSw2pm0RSP9Q';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-122.486052, 37.830348],
zoom: 15
});
map.on('load', function () {
map.addLayer({
"id": "route",
"type": "line",
"source": {
"type": "geojson",
"data": {
"type": "Feature",
"properties": {},
"geometry": {
"type": "LineString",
"coordinates": [
[-122.48369693756104, 37.83381888486939],
[-122.48348236083984, 37.83317489144141],
[-122.48339653015138, 37.83270036637107],
[-122.48356819152832, 37.832056363179625],
[-122.48404026031496, 37.83114119107971],
[-122.48404026031496, 37.83049717427869],
[-122.48348236083984, 37.829920943955045],
[-122.48356819152832, 37.82954808664175],
[-122.48507022857666, 37.82944639795659],
[-122.48610019683838, 37.82880236636284],
[-122.48695850372314, 37.82931081282506],
[-122.48700141906738, 37.83080223556934],
[-122.48751640319824, 37.83168351665737],
[-122.48803138732912, 37.832158048267786],
[-122.48888969421387, 37.83297152392784],
[-122.48987674713133, 37.83263257682617],
]
}
}
},
"layout": {
//"line-join": "round",
"line-cap": "round"
},
"paint": {
"line-color": "#888",
"line-width": 6
}
});
var dashLength = 1;
var gapLength = 13;
// We divide the animation up into 40 steps to make careful use of the finite space in LineAtlas //
var steps = 24;
// A # of steps proportional to the dashLength are devoted to manipulating the dash
var dashSteps = steps * dashLength / (gapLength + dashLength);
// A # of steps proportional to the gapLength are devoted to manipulating the gap
var gapSteps = steps - dashSteps;
// The current step #
var step = 0;
setInterval(function() {
step = step + 1;
if (step >= steps) step = 0;
var t, a, b, c, d;
if (step < dashSteps) {
t = step / dashSteps;
a = (1 - t) * dashLength;
b = gapLength;
c = t * dashLength;
d = 0;
} else {
t = (step - dashSteps) / (gapSteps);
a = 0;
b = (1 - t) * gapLength;
c = dashLength;
d = t * gapLength;
}
map.setPaintProperty("route", "line-dasharray", [a, b, c, d]);
}, 125);
map.setPaintProperty("route", "line-dasharray", [1, 2, 1, 4]);
});
</script>
</body>
</html>
TLDR: I have an NVD3 graph that shows tick lines all across the axis, but I would like to change it so it only displays on the axis lines if possible.
Here is a live example:
var app = angular.module('plunker', ['nvd3']);
app.controller('MainCtrl', function($scope) {
$scope.options = {
chart: {
type: 'lineChart',
height: 450,
margin : {
top: 20,
right: 20,
bottom: 80,
left: 55
},
x: function(d){ return d.x; },
y: function(d){ return d.y; },
useInteractiveGuideline: true,
xAxis: {
axisLabel: 'Timeline',
tickFormat: function(d) {
return d3.time.format('%B %d')(new Date(d))
},
ticks: 6,
showMaxMin: false
},
yAxis: {
axisLabel: 'Molecular density (kg/m^3)',
tickFormat: function(d){
return d3.format('.02f')(d);
},
axisLabelDistance: -10,
showMaxMin: false
}
}
};
$scope.data = [{"key":"K7 molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":9},{"x":1435881600000,"y":8},{"x":1435968000000,"y":8},{"x":1436054400000,"y":9},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":8},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":7},{"x":1436659200000,"y":8}],"area":true,"color":"#0CB3EE"},{"key":"N41 type C molecules","values":[{"x":1435708800000,"y":8},{"x":1435795200000,"y":7},{"x":1435881600000,"y":8},{"x":1435968000000,"y":9},{"x":1436054400000,"y":7},{"x":1436140800000,"y":9},{"x":1436227200000,"y":8},{"x":1436313600000,"y":9},{"x":1436400000000,"y":9},{"x":1436486400000,"y":9},{"x":1436572800000,"y":9},{"x":1436659200000,"y":8}],"area":true,"color":"#383838"}];
});
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>Angular-nvD3 Line Chart</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.css"/>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.1/nv.d3.min.js"></script>
<script src="https://rawgit.com/krispo/angular-nvd3/v1.0.1/dist/angular-nvd3.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<nvd3 options="options" data="data" class="with-3d-shadow with-transitions"></nvd3>
</body>
</html>
Is there any way I could make the tick lines appear just on the axes line only? To make it clear, this is what it looks like:
I used a different library to generate the following plot, and I would like the tick lines to appear just on the axis lines like this example instead:
It appears that there is no real way to do this with NVD3 as it does not provide a way to show tick marks on the axis. However, we could add our own tick marks by fetching the chart SVG and then modifying it.
I've attached an example that adds tick marks to X-Axis, and it is basically slightly modified based on this jsfiddle here: http://jsfiddle.net/3r88bgjw
var data;
data = [{
values: [],
}, ];
var i, x;
var prevVal = 3000;
var tickCount = 2000;
for (i = 0; i < tickCount; i++) {
x = 1425096000 + i * 10 * 60; // data points every ten minutes
if (Math.random() < 0.8) { // add some gaps
prevVal += (Math.random() - 0.5) * 500;
if (prevVal <= 0) {
prevVal = Math.random() * 100;
}
data[0].values.push({
x: x * 1000,
y: prevVal
});
}
}
var chart;
nv.addGraph(function() {
chart = nv.models.historicalBarChart();
chart.xScale(d3.time.scale()) // use a time scale instead of plain numbers in order to get nice round default values in the axis
.color(['#68c'])
.useInteractiveGuideline(true) // check out the css that turns the guideline into this nice thing
.margin({
"left": 80,
"right": 50,
"top": 20,
"bottom": 30,
})
.noData("There is no data to display.")
.duration(0);
var tickMultiFormat = d3.time.format.multi([
["%-I:%M%p", function(d) {
return d.getMinutes();
}], // not the beginning of the hour
["%-I%p", function(d) {
return d.getHours();
}], // not midnight
["%b %-d", function(d) {
return d.getDate() != 1;
}], // not the first of the month
["%b %-d", function(d) {
return d.getMonth();
}], // not Jan 1st
["%Y", function() {
return true;
}]
]);
chart.xAxis
.showMaxMin(false)
.tickPadding(10)
.tickFormat(function(d) {
return tickMultiFormat(new Date(d));
});
chart.yAxis
.tickFormat(d3.format(",.0f"));
var svgElem = d3.select('#chart svg');
svgElem
.datum(data)
.transition()
.call(chart);
// make our own x-axis tick marks because NVD3 doesn't provide any
var tickY2 = chart.yAxis.scale().range()[1];
var lineElems = svgElem
.select('.nv-x.nv-axis.nvd3-svg')
.select('.nvd3.nv-wrap.nv-axis')
.select('g')
.selectAll('.tick')
.data(chart.xScale().ticks())
.append('line')
.attr('class', 'x-axis-tick-mark')
.attr('x2', 0)
.attr('y1', tickY2 + 7)
.attr('y2', tickY2)
.attr('stroke-width', 3);
// set up the tooltip to display full dates
var tsFormat = d3.time.format('%b %-d, %Y %I:%M%p');
var contentGenerator = chart.interactiveLayer.tooltip.contentGenerator();
var tooltip = chart.interactiveLayer.tooltip;
tooltip.contentGenerator(function(d) {
d.value = d.series[0].data.x;
return contentGenerator(d);
});
tooltip.headerFormatter(function(d) {
return tsFormat(new Date(d));
});
return chart;
});
<div>Try resizing the panel to see the various types of time labels.</div>
<br>
<div id="chart">
<svg></svg>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/nvd3/1.8.4/nv.d3.min.js"></script>
The first time I load data, the graph draws correctly, but when I load a different data set, the graph remains unchanged.
I switch between datasets using buttons. The first click always draws the graph correctly, no matter what button I click. But I can't update the graph after it is drawn by clicking on the other button. Any help is very much appreciated,thank you!
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 900;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale
.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
});
bar
.append("rect")
.attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
CodePen: https://codepen.io/rfripp2/pen/porpaLL
This is the expected behavior. Let's look at your code:
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
The select all statement selects all existing elements matching the selector that are children of elements in the selection chart.
The data method binds a new data array to this selection.
The enter method returns a new selection, containing a placeholder for every item in the data array which does not have a corresponding element in the selection.
The append method returns a newly appended child element for every element in the selection it is called on.
Running the code
The first time you call the draw function you have no g elements, so the selection is empty. You bind data to this empty selection. You then use the enter selection. Because there are two data items and no elements in the selection, enter contains two placeholders/elements. You then use append to add those elements.
The second time you call the draw function you have two g elements, so the selection has two elements in it. You bind data to this selection. You then use the enter selection. Because you already have two elements and you only have two data points, the enter selection is empty. As a consequence, append does not create any new elements.
You can see this by using selection.size():
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 900;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale
.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("g")
.data(dataSet)
.enter()
.append("g")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
});
console.log("The enter selection contains: " + bar.size() + "elements")
bar
.append("rect")
.attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
<script src="https://d3js.org/d3.v4.js"></script>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Solution
We want to use both the update and the enter selection (if the dataset ever changes in size, we'd likely want the exit selection too). We can use .join() to simplify this, join removes elements in the exit selection (surplus elements which don't have a corresponding data item), and returns the merged enter selection (new elements for surplus data items) and update selection (preexisting elements).
The nesting of your elements into a parent g and child rect is unnecessary here - and requires additional modifications. By positioning the bars directly we avoid the need for the parent g:
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scaleBand().range([0, width], 0.9);
let y = d3.scaleLinear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("rect")
.data(dataSet)
.join("rect")
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.0.0/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
This requires updating your version of D3 from v3 (you are actually using two versions of D3, v3 and v4, both fairly outdated, and both with different method names, actually with different ways of handling the enter selection).
If you wish to use d3v4, then the join method is not available, but we can merge enter and update:
When I say update selection, I'm refering to the initial selection:
// update selection:
let bar = chart
.selectAll("rect")
.data(dataSet);
// enter selection:
bar.enter().append("rect")
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scaleBand().range([0, width], 0.9);
let y = d3.scaleLinear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
let bar = chart
.selectAll("rect")
.data(dataSet);
bar.enter().append("rect")
.merge(bar)
.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.0/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
And lastly, if you wish to keep d3v3 (we are on v7 already), we can rely on an implicit merging of update and enter on enter (modifying the update selection). This "magic" was removed in v4, partly because it was not explicit. To do so we need to break your method chaining so that bar contains the
const dataA = [
{ population: 50, size: 100 },
{ population: 100, size: 100 },
];
const dataB = [
{ money: 4, currency: "usd" },
{ money: 10, currency: "eur" },
];
function drawChart(dataSet, prop) {
let width = 400;
let height = 200;
let x = d3.scale.ordinal().rangeRoundBands([0, width], 0.9);
let y = d3.scale.linear()
.domain([dataSet[0][prop] - 39, dataSet[dataSet.length - 1][prop]])
.range([height, 0]);
let chart = d3.select("#chart").attr("width", width).attr("height", height);
let barWidth = width / dataSet.length;
let div = d3.select("body").append("div").attr("class", "tooltip");
// update selection:
let bar = chart
.selectAll("rect")
.data(dataSet);
// enter selection:
bar.enter().append("rect")
bar.attr("transform", function (d, i) {
return "translate(" + i * barWidth + ",0)";
}).attr("y", function (d) {
return y(d[prop]);
})
.attr("height", function (d) {
return height - y(d[prop]);
})
.attr("width", barWidth);
}
function drawDataA() {
drawChart(dataA, "population");
}
function drawDataB() {
drawChart(dataB, "money");
}
d3.select("#dataA").on("click", drawDataA);
d3.select("#dataB").on("click", drawDataB);
<!DOCTYPE html>
<html>
<meta charset="utf-8" />
<head>
</head>
<body>
<div id="app">
<svg class="chart" id="chart"></svg>
<br />
<button id="dataA">data1</button>
<button id="dataB">data2</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Note: d3v4 made changes to method names that break code from v3. This required changes to d3.scale.linear / d3.scale.ordinal in the snippets using v4 and 7 (using merge and join respectively).
I have the following data array:
ID Name Number
---- ------ --------
1 G 1
1 G 2
1 F 3
I want to do the following conversion to calculate the average, but I don’t know how to do it.
ID Name Number_sum
---- ------ ------------
1 G 3
1 F 3
after summing calculate the average
ID Number_avg
---- ------------
1 3
If you do not pre-sum, then the average value is calculated incorrectly:
ID Number_avg
---- ------------
1 2
I want to calculate the average value for each ID, but with an even field "Name".
Next, I plan to build a graph for each ID. I have a road identifier - 1. This road consists of 2 sections: G and F. Moreover, section G is divided into 2 more small sections, 1 and 2 km each.
If we consider the usual average value, then we get the average value over the maximum section of the value - a sub-section of the road. But I want to make a calculation based on the average value of the road sections.
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js</title>
<meta charset="UTF-8">
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/d3.js"></script>
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/crossfilter.js"></script>
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/dc.js"></script>
</head>
<body>
<div id ="test"></div>
<script type="text/javascript">
//dc.js
var inlineND = new dc.NumberDisplay("#test");
//data
var array1 = [
{"ID": 1, "Name": "G", "Number": 1},
{"ID": 1, "Name": "G", "Number": 2},
{"ID": 1, "Name": "F", "Number": 3}
];
var make_calc = function() {
var ndx = crossfilter(array1), //
Dimension = ndx.dimension(function(d) {return d.ID;}),
DimensionGroup = Dimension.group().reduce(reduceAdd, reduceRemove, reduceInitial);
function reduceAdd(p, v) {
++p.count;
p.total += v.Number;
return p;
}
function reduceRemove(p, v) {
--p.count;
p.total -= v.Number;
return p;
}
function reduceInitial() {
return {count: 0, total: 0};
}
inlineND
.group(DimensionGroup)
.valueAccessor(function(p) { return p.value.count > 0 ? p.value.total / p.value.count : 0; });
dc.renderAll();
//console.log(DimensionGroup);
};
make_calc();
</script>
</body>
</html>
In order to calculate the average, taking into account the "Name" field, it is necessary to consider the unique occurrence of this field in the reduce function. As a result, when calculating the average value, divide the sum of values by the number of unique values in the "Name" field
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js</title>
<meta charset="UTF-8">
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/d3.js"></script>
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/crossfilter.js"></script>
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/dc.js"></script>
</head>
<body>
<div id ="test"></div>
<script type="text/javascript">
//dc.js
var inlineND = new dc.NumberDisplay("#test");
//data
var array1 = [
{"ID": 1, "Name": "G", "Number": 1},
{"ID": 1, "Name": "G", "Number": 2},
{"ID": 1, "Name": "F", "Number": 3}
];
var make_calc = function() {
var ndx = crossfilter(array1), //
Dimension = ndx.dimension(function(d) {return d.ID;}),
DimensionGroup = Dimension.group().reduce(reduceAdd, reduceRemove, reduceInitial);
function reduceAdd(p, v) {
++p.count;
p.total += v.Number;
if(v.Name in p.Names){
p.Names[v.Name] += 1
}
else{
p.Names[v.Name] = 1;
p.Name_count++;
};
return p;
}
function reduceRemove(p, v) {
--p.count;
p.total -= v.Number;
p.Names[v.Name]--;
if(p.Names[v.Name] === 0){
delete p.Names[v.Name];
p.Name_count--;
};
return p;
}
function reduceInitial() {
return {count: 0, total: 0, Name_count: 0, Names: {}};
}
inlineND
.group(DimensionGroup)
.valueAccessor(function(p) { return p.value.Name_count > 0 ? p.value.total / p.value.Name_count : 0; });
dc.renderAll();
//console.log(DimensionGroup);
};
make_calc();
</script>
</body>
</html>
I'm not sure, but are you looking for something like this?
const arr = [
{id: 1, name: 'G', number: 1},
{id: 2, name: 'G', number: 2},
{id: 3, name: 'F', number: 3}
]
const res = arr.reduce((acc, e) => {
const idx = acc.findIndex(x => x.name === e.name)
if (idx !== -1) {
acc[idx].number += e.number
} else {
acc.push(e)
}
return acc
}, [])
console.log(res)
I'm not sure if I completely understand, but if you want to group by Name, sum, and and then take the average of all groups, you could put your dimension on Name and use regular reduceSum:
var ndx = crossfilter(array1), //
Dimension = ndx.dimension(function(d) {return d.Name;}),
DimensionGroup = Dimension.group().reduceSum(d => d.Number);
Then pass a "fake groupAll" which returns all the rows from the group to the number display, and calculate the average in the value accessor:
.group({value: () => DimensionGroup.all()})
.valueAccessor(a => a.length === 0 ? 0 : d3.sum(a, ({value}) => value) / a.length);
<!DOCTYPE html>
<html lang="en">
<head>
<title>dc.js</title>
<meta charset="UTF-8">
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/d3.js"></script>
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/crossfilter.js"></script>
<script type="text/javascript" src="https://dc-js.github.io/dc.js/js/dc.js"></script>
</head>
<body>
<div id ="test"></div>
<script type="text/javascript">
//dc.js
var inlineND = new dc.NumberDisplay("#test");
//data
var array1 = [
{"ID": 1, "Name": "G", "Number": 1},
{"ID": 1, "Name": "G", "Number": 2},
{"ID": 1, "Name": "F", "Number": 3}
];
var make_calc = function() {
var ndx = crossfilter(array1), //
Dimension = ndx.dimension(function(d) {return d.Name;}),
DimensionGroup = Dimension.group().reduceSum(d => d.Number);
inlineND
.group({value: () => DimensionGroup.all()})
.valueAccessor(a => a.length === 0 ? 0 : d3.sum(a, ({value}) => value) / a.length);
dc.renderAll();
//console.log(DimensionGroup);
};
make_calc();
</script>
</body>
</html>
I am trying to display a graph with images and labels with GraphViz. I would like to display the label under the image (see labelloc="b" option on the graph) but somehow it doesn't not work. Label and image are overlapped.
Any idea what I am missing?
Below is the DOT code I am using, and the current result.
Thanks!
digraph {
graph [compound=true, labelloc="b"];
node [shape=box];
edge [dir=none];
Label1[label="Label1",image="images/Avatar1.png"];
Label2[label="Label2",image="images/Avatar2.png"];
Label3[label="Label3",image="images/Avatar3.png"];
{
rank=same;
Label1 -> h0 -> Label2;
h0[shape=circle,label="",height=0.01,width=0.01];
}
{
h0_0;
h0_0[shape=circle,label="",height=0.01,width=0.01];
}
h0 -> h0_0;
h0_0 -> Label3;
}
UPD: You need just to add an imagepos attribute to your solution with height:
digraph {
graph [compound=true, labelloc="b"];
node [shape=box];
edge [dir=none];
Label1[
label="Label1"
height="2.1"
imagepos="tc"
labelloc="b"
image="images/Avatar1.png"
];
Label2[
label="Label2"
height="2.1"
imagepos="tc"
labelloc="b"
image="images/Avatar2.png"
];
Label3[
label="Label3"
height="2.1"
imagepos="tc"
labelloc="b"
image="images/Avatar3.png"
];
{
rank=same;
Label1 -> h0 -> Label2;
h0[shape=circle,label="",height=0.01,width=0.01];
}
{
h0_0;
h0_0[shape=circle,label="",height=0.01,width=0.01];
}
h0 -> h0_0;
h0_0 -> Label3;
}
Result:
Or you may also use HTML-like labels, and specifically, tables:
digraph {
graph [compound=true, labelloc="b"];
node [shape=box];
edge [dir=none];
Label1 [
shape=plain
label=<
<table cellspacing="0" border="0" cellborder="1">
<tr><td><img src="images/Avatar1.png" /></td></tr>
<tr><td>Label1</td></tr>
</table>
>
];
Label2 [
shape=plain
label=<
<table cellspacing="0" border="0" cellborder="1">
<tr><td><img src="images/Avatar2.png" /></td></tr>
<tr><td>Label2</td></tr>
</table>
>
];
Label3 [
shape=plain
label=<
<table cellspacing="0" border="0" cellborder="1">
<tr><td><img src="images/Avatar3.png" /></td></tr>
<tr><td>Label3</td></tr>
</table>
>
];
{
rank=same;
Label1 -> h0 -> Label2;
h0[shape=circle,label="",height=0.01,width=0.01];
}
{
h0_0;
h0_0[shape=circle,label="",height=0.01,width=0.01];
}
h0 -> h0_0;
h0_0 -> Label3;
}
The code is a bit more complex (at first glance), but as a bonus you get more flexible control over the borders.
Result:
By specifying a "height" (warning, those are "inches") for the nodes, I get the "labelloc" to work and I can thus move the label out of the picture. I would prefer if the box didn't have that white place at the top, but it's better than before.