how to put dynamic data text inside rectangle in d3 - d3.js

Update method : Thanks in advance. I am creating rectangles based on the api response data. The rectangles will will be removed and re-created when the new data come back from api. I want to achieve same thing for adding text inside the rectangles, means as soon as I receive the fresh data text should be overrided or re-created based on the data.
/* update selection*/
var rectangles = vis.ganttSvgRef.selectAll("rect").data(chartData);
/*exit selection*/
rectangles.exit().remove();
/*enter selection*/
var innerRects = rectangles.enter().append("rect").merge(rectangles)
.attr("x", function (d) {
return vis.timeScale(parseTime(d.arrivalTime_data)) + sidePadding;
})
.attr("y", function (d, i) {
for (var j = 0; j < slotNumber.length; j++) {
if (d.slot == slotNumber[j]) {
return vis.yScale(d.slot);
}
}
})
.attr("width", function (d) {
return (vis.timeScale(parseTime(d.departureTime_data)) -
vis.timeScale(parseTime(d.arrivalTime_data)));
})
.attr("height", barHeight)
.attr("stroke", "none")
.attr("fill", function (d) {
for (var i = 0; i < vesselsNames.length; i++) {
return serviceColorSelector[d.serviceName_data]
}
})
how to add the text in the rectangles in middle, which should also get update based on the data receive. Thanks
Updated code as suggested by #Michael Rovinsky : This code works perfectly fine for appending the text inside the rect, but on few rect the text is overflowing outside the rect area. I don't want to show the text if it overflow from rect area or how can i hide the text if it overflow from rect area ?
var rectangles = vis.ganttSvgRef.selectAll("rect")
.data(chartData);
rectangles.exit().remove();
var innerRects = rectangles.enter().append("g");
let rectinst = innerRects.append("rect").merge(rectangles)
.attr("x", function (d) {
return vis.timeScale(parseTime(d.arrivalTime_data)) +
sidePadding;
})
.attr("y", function (d, i) {
for (var j = 0; j < slotNumber.length; j++) {
if (d.slot == slotNumber[j]) {
return vis.yScale(d.slot);
}
}
})
.attr("width", function (d) {
return (vis.timeScale(parseTime(d.departureTime_data)) -
vis.timeScale(parseTime(d.arrivalTime_data)));
})
.attr("height", barHeight)
.attr("stroke", "none")
.attr("fill", function (d) {
for (var i = 0; i < vesselsNames.length; i++) {
return serviceColorSelector[d.serviceName_data]
}
})
let text = vis.ganttSvgRef.selectAll(".rect-text")
.data(chartData);
text.exit().remove();
innerRects.append("text").merge(text)
.attr("class", 'rect-text')
.text(function (d) {
let rectWidth = (vis.timeScale(parseTime(d.departureTime_data)) -
vis.timeScale(parseTime(d.arrivalTime_data)));
console.log("rect width : ", rectWidth)
console.log("d.vesselName_data : ",
vis.timeScale(d.vesselName_data.length))
return d.vesselName_data;
})
.attr("x", function (d) {
return (vis.timeScale(parseTime(d.departureTime_data)) -
vis.timeScale(parseTime(d.arrivalTime_data))) / 2 +
vis.timeScale(parseTime(d.arrivalTime_data)) + sidePadding;
})
.attr("y", function (d, i) {
for (var j = 0; j < slotNumber.length; j++) {
if (d.slot == slotNumber[j]) {
return vis.yScale(d.slot) + (barHeight / 2);
}
}
})
.attr("font-size", barHeight / 2)
.attr("text-anchor", "middle")
.attr("text-height", barHeight)
.attr("fill", '#fff');

Append "g" instead of "rect" on enter():
const containers = rectangles.enter().append("g");
Append "rect" and "text" under "g":
containers.append("rect").attr('width', ...).attr('height', ...)...
containers.append("text").text('My Text Here')...

You can write your own text wrapping function d3 based on the rect dimensions and given padding.
Please check following link for customised text wrapping and overflow control in d3.js-
Code- text-wrapping-in-d3
function wrap(text) {
text.each(function() {
var text = d3.select(this);
var words = text.text().split(/\s+/).reverse();
var lineHeight = 20;
var width = parseFloat(text.attr('width'));
var y = parseFloat(text.attr('y'));
var x = text.attr('x');
var anchor = text.attr('text-anchor');
var tspan = text.text(null).append('tspan').attr('x', x).attr('y', y).attr('text-anchor', anchor);
var lineNumber = 0;
var line = [];
var word = words.pop();
while (word) {
line.push(word);
tspan.text(line.join(' '));
if (tspan.node().getComputedTextLength() > width) {
lineNumber += 1;
line.pop();
tspan.text(line.join(' '));
line = [word];
tspan = text.append('tspan').attr('x', x).attr('y', y + lineNumber * lineHeight).attr('anchor', anchor).text(word);
}
word = words.pop();
}
});
}
function dotme(text) {
text.each(function() {
var text = d3.select(this);
var words = text.text().split(/\s+/);
var ellipsis = text.text('').append('tspan').attr('class', 'elip').text('...');
var width = parseFloat(text.attr('width')) - ellipsis.node().getComputedTextLength();
var numWords = words.length;
var tspan = text.insert('tspan', ':first-child').text(words.join(' '));
// Try the whole line
// While it's too long, and we have words left, keep removing words
while (tspan.node().getComputedTextLength() > width && words.length) {
words.pop();
tspan.text(words.join(' '));
}
if (words.length === numWords) {
ellipsis.remove();
}
});
}
d3.selectAll('.wrapme').call(wrap);
d3.selectAll('.dotme').call(dotme);

Related

d3.js click and apply zoom and pan to distribute points located inside a targeted division to the triggered subdivisions

Based on the response and example made by Andrew Reid, I produced this
pen code here points_in_subdivisons: on clicking on areas(Germany) on the screen
We want to offer a smooth animation from one close-up on the map to another
by using ZOOM OUT, PAN, ZOOM IN.
I have many divisions(countries) on Country level and then many sub-divisions(regions) inside each country .
Many points scattered across all divisions (countries) on my example mainly above Germany.
when I have to click on a targeted division(country) I must get only the points which correspond to this targeted division(country) that I have just clicked on
That means when the zoom of the subdivision(regions) is triggered(when the click is
made),
the code should take all the points that exist already only inside the
contours of the targeted divison(country) (that have just been clicked on) and points
enclosed-in should scatter in their corresponding subdivisions(regions).
To achieve this functionality and
based on Michael Rovinsky comment:
in the function manipulate(), the code is able to filter and extract only points that are embedded inside the targeted and triggered subdivisions(regions) and exclude markers those that are outside.
Inside function redraw() the enter exit pattern works well .
var svg = d3.select("svg");
width = 960;
height = 500;
var dataArray = [];
var mydataArray= [];
var projection = d3.geoMercator();
var baseProjection = d3.geoMercator();
var path = d3.geoPath().projection(projection);
var gBackground = svg.append("g"); // appended first
var gProvince = svg.append("g");
var gDataPoints = svg.append("g"); // appended second
var ttooltip = d3.select("body").append("div")
.attr("class", "ttooltip");
var csvPath="https://dl.dropbox.com/s/rb9trt4zy87ezi3/lonlat.csv?dl=0";
d3.csv(csvPath, function(error, data) {
if (error) throw error;
d3.json("https://gist.githubusercontent.com/rveciana/5919944/raw/2fef6be25d39ebeb3bead3933b2c9380497ddff4/nuts0.json", function(error, nuts0) {
if (error) throw error;
d3.json("https://gist.githubusercontent.com/rveciana/5919944/raw/2fef6be25d39ebeb3bead3933b2c9380497ddff4/nuts2.json", function(error, nuts2) {
if (error) throw error;
// convert topojson back to geojson
var countries = topojson.feature(nuts0, nuts0.objects.nuts0);
var regions = topojson.feature(nuts2, nuts2.objects.nuts2);
baseProjection.fitSize([width,height],regions);
projection.fitSize([width,height],regions);
var color = d3.scaleLinear().range(["steelblue","darkblue"]).domain([0,countries.features.length]);
var regionColor = d3.scaleLinear().range(["orange","red"]);
baseProjection.fitSize([width,height],countries);
projection.fitSize([width,height],countries);
var featureCollectionCountries = { "type":"FeatureCollection", "features": countries.features };
gBackground
.attr("class", "country")
.selectAll("path")
.data(countries.features)
.enter()
.append("path")
.attr("fill",function(d,i) { return color(i); })
.attr("opacity",0.7)
.attr("d", path)
.style("stroke","black")
.style("stroke-width",0)
.on("mouseover", function() {
d3.select(this)
.style("stroke-width",1)
.raise();
})
.on("mouseout", function(d,i) {
d3.select(this)
.style("stroke-width", 0 );
})
///// now zoom in when clicked and show subdivisions:
.on("click", function(d) {
// remove all other subdivisions:
d3.selectAll(".region")
.remove();
// add new features:
var features = regions.features.filter(function(feature) { return feature.properties.nuts_id.substring(0,2) == d.properties.nuts_id; });
regionColor.domain([0,features.length])
gProvince.selectAll(null)
.data(features)
.enter()
.append("path")
.attr("class","region")
.attr("fill", function(d,i) { return regionColor(i) })
.attr("d", path)
.style("stroke","black")
.style("stroke-width",0)
.on("click", function() {
zoom(projection,baseProjection);
d3.selectAll(".subdivision")
.remove();
})
.on("mouseover", function() {
d3.select(this)
.style("stroke-width",1)
.raise();
})
.on("mouseout", function(d,i) {
d3.select(this)
.style("stroke-width", 0 );
})
.raise()
// zoom to selected features:
var featureCollection = { "type":"FeatureCollection", "features": features }
manipulate(data,features);
redraw(featureCollection);
var endProjection = d3.geoMercator();
zoom(projection,endProjection.fitExtent([[50,50],[width-50,height-50]],featureCollection));
});
dataArray = data;
redraw(featureCollectionCountries);
});
});
});
function zoom(startProjection,endProjection,middleProjection) {
if(!middleProjection) {
d3.selectAll("path")
.transition()
.attrTween("d", function(d) {
var s = d3.interpolate(startProjection.scale(), endProjection.scale());
var x = d3.interpolate(startProjection.translate()[0], endProjection.translate()[0]);
var y = d3.interpolate(startProjection.translate()[1], endProjection.translate()[1]);
return function(t) {
projection
.scale(s(t))
.translate([x(t),y(t)])
path.projection(projection);
return path(d);
}
})
.duration(1000);
}
else {
d3.selectAll("path")
.transition()
.attrTween("d", function(d) {
var s1 = d3.interpolate(startProjection.scale(),middleProjection.scale());
var s2 = d3.interpolate(middleProjection.scale(),endProjection.scale());
var x = d3.interpolate(startProjection.translate()[0], endProjection.translate()[0]);
var y = d3.interpolate(startProjection.translate()[1], endProjection.translate()[1]);
function s(t) {
if (t < 0.5) return s1; return s2;
}
return function(t) {
projection
.translate([x(t),y(t)])
.scale(s(t)(t))
path.projection(projection);
return path(d);
}
})
.duration(1500);
}
}
function redraw(featureCollection,type) {
var mapG = d3.select('svg g.country');
d3.selectAll('circle')
.remove();
let grp = gDataPoints
.attr("class", "circle")
.selectAll("circle")
.data(dataArray,function(d) { return d.NOM; })
let grpEnter = grp.enter()
let group = grpEnter
group.append("circle")
.attr('fill', 'rgba(135, 5, 151, 125)')
.attr('stroke', 'black')
.each(function(d) {
if (d.lon === null ) return;
if (isNaN(d.lon ))return;
if (d.lat === null) return;
if (isNaN(d.lat ))return;
var pos = projection([parseFloat(d.lon), parseFloat(d.lat)]);
d.cx = pos[0];
d.cy = pos[1];
})
.attr("cx", function(d) {
return d.cx;
})
.attr("cy", function(d) {
return d.cy;
})
.attr("r",0.5)
.on("mouseover", showTooltip)
.on("mouseout", hideTooltip)
.on('mousemove', function(d) {
var xPos = d3.mouse(this)[0] - 15;
var yPos = d3.mouse(this)[1] - 55;
ttooltip.attr('transform', 'translate(' + xPos + ',' + yPos + ')');
ttooltip.style('opacity', 1);
var html = "<span>" + d.lon+ "</span>, <span>" + d.lat + "</span>";
ttooltip.html(html);
});
// Setup each circle with a transition, each transition working on transform attribute,
// and using the translateFn
group
.transition()
.duration(2000)
.attrTween("transform",function(d) {
return mapG._groups[0][0] != null ? recenter(featureCollection): null;
});
group.exit().remove() // exit > remove > g
}
function recenter(featureCollection) {
console.log('recentering');
};
function manipulate(data,features){
dataArray= [];
mydataArray =[];
data.forEach(function(ddd)
{
features.forEach(function(feature)
{
var polygoneOriginal =feature;
var points = [parseFloat(ddd.lon), parseFloat(ddd.lat)];
var isIn = d3.geoContains(polygoneOriginal, points);
if(isIn)
{
var element = ddd;
mydataArray.pushIfNotExist(element, function(e) {
return e.lat === element.lat && e.lon === element.lon ;
});
}
});
});
if(mydataArray.length>0)
{
var columnsArray= ["lon","lat"];
dataArray=mydataArray;
dataArray.columns = columnsArray;
}
}
function showTooltip(d) {
var html = "<span>" + d.lon+ "</span>, <span>" + d.lat + "</span>";
ttooltip.html(html);
ttooltip
.style("left", window.pageXOffset + d3.event.x + 12 + "px")
.style("top", window.pageYOffset + d3.event.y + 12 + "px")
.transition()
.style("opacity", 1);
return d3.select(this).attr('fill', 'rgba(103, 65, 114, 0.8)');
}
function hideTooltip() {
ttooltip
.transition()
.style("opacity", 0);
return d3.select(this).attr('fill', 'rgba(103, 65, 114, 0.5)');
}
// check if an element exists in array using a comparer function
// comparer : function(currentElement)
Array.prototype.inArray = function(comparer) {
for(var i=0; i < this.length; i++) {
if(comparer(this[i])) return true;
}
return false;
};
// adds an element to the array if it does not already exist using a comparer
// function
Array.prototype.pushIfNotExist = function(element, comparer) {
if (!this.inArray(comparer)) {
this.push(element);
}
};
My Question is the following : How to make the Zooming (for points circle) to work adequately:
right now, on a map upon click the x y points not scale.
They are rendered as circles in background and I would like them to move with the map.
That means How to apply the same animation zoom (when subdivisions are triggered by click on a division) in order to those points inside the targeted subdivision follow in transition and move with the map and we could see circles points clearly distributed adequately in each correct corresponding subdivisions?
update
Andrew Reid described here How To accomplish a smooth zoom using d3.js
so following his hints.
I added the following instructions in redraw() function
var mapG = d3.select('svg g.country');
group
.transition()
.duration(2000)
.attrTween("transform",function(d) {
return mapG._groups[0][0] != null ? recenter(): null;
});
AND then we should add the code to the The function that should actually do the moving recenter(featureCollection) function to
function recenter(featureCollection) {
// TO ADD CODE TO BE IMPLEMENTED HERE
};
Thank You very much for your cooperation,participation and help !
1- To generate first iteration click on Region equal country
//GENERATE FIRST MAP
dataArray = data;
redraw();
2- To generate counties for example on click on region, we should first set startprojection and endprojection in zoom function and then trigger redraw of circles
//zoom to selected provinces features:
var countiesFeatureCollection = { "type":"FeatureCollection", "features": countiesFeatures }
//manipulate counties And Redraw
manipulateCounties(data,countiesFeatures);
baseProjection.fitExtent([[50,50],[width-50,height-50]],countiesFeatureCollection);
projection.fitExtent([[50,50],[width-50,height-50]],countiesFeatureCollection);
redraw(countiesFeatureCollection,"counties");
if ( projection.translate().toString() === baseProjection.translate().toString() && projection.scale() === baseProjection.scale() )
{
zoom(baseProjection,projection.fitExtent([[50,50],[width-50,height-50]],countiesFeatureCollection));
}
else
{
var endProjection = d3.geoMercator();
zoom(projection,endProjection.fitExtent([[50,50],[width-50,height-50]],countiesFeatureCollection));
}
3-the same thing should be applied to communities
var endProjection = d3.geoMercator();
endProjection.fitExtent([[50,50],[width-50,height-50]],communesfeatureCollection);
projection.fitExtent([[50,50],[width-50,height-50]],communesfeatureCollection);
redraw(communesfeatureCollection,"communes");
if ( projection.translate().toString() === projectioncommune.translate().toString() && projection.scale() === projectioncommune.scale()){
zoom(projectioncommune,projection.fitExtent([[50,50],[width-50,height-50]],communesfeatureCollection));
}
else {
var endProjection = d3.geoMercator();
zoom(projection,endProjection.fitExtent([[50,50],[width-50,height-50]],communesfeatureCollection));
}
4- Then reinitialise to go to first step 1 by
// start rendering points again
baseProjection.fitSize([width,height],regions);
projection.fitSize([width,height],regions);
//GENERATE AGAIN THE FIRST MAP
dataArray = data;
redraw();
zoom(projection,baseProjection);
ATTACHED WORKING PEN

consolidate successive translations in D3

The following toy code (jsfiddle here) write to the console log translate(20,0) translate(20,0) translate(20,0) translate(20,0) translate(20,0).
Is it possible to get translate(100,0) as a "consolidated" translation?
var svg = d3.select('svg');
var rec=svg.append("rect")
.attr("width",20)
.attr("height", 20)
.attr("x", 0)
.attr("y", 20)
.attr("fill","#00ffff")
.attr("transform","")
;
for (var i=0;i<10;i++) {
rec
.attr("transform",rec.attr("transform")+" translate(20,0)")
;
}
console.log(rec.attr("transform"))
First of all, I believe you want to get translate(200,0) as the result, not translate(100,0), since there are 10 loops.
That being said, you have to get the translate values and add 20 to the first one and 0 to the second one. Otherwise you'll just concatenate strings, as you are doing right now.
Unfortunately there is no native method in D3 v4/v5 to get the transform value, so I'll use the function provided in this answer, with a slight modification (the if conditional), since your first value is an empty string (""):
function getTranslation(transform) {
if (transform === "") {
return [0, 0]
};
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.setAttributeNS(null, "transform", transform);
var matrix = g.transform.baseVal.consolidate().matrix;
return [matrix.e, matrix.f];
}
So, all you need is to get the current translate and add the value you want in your for loop:
for (var i = 0; i < 10; i++) {
var currentTransform = getTranslation(rec.attr("transform"));
rec.attr("transform", "translate(" + (currentTransform[0] + 20) + ",0)");
}
Here is the demo:
var svg = d3.select('svg');
var rec = svg.append("rect")
.attr("width", 20)
.attr("height", 20)
.attr("x", 0)
.attr("y", 20)
.attr("fill", "#00ffff")
.attr("transform", "");
for (var i = 0; i < 10; i++) {
var currentTransform = getTranslation(rec.attr("transform"));
rec.attr("transform", "translate(" + (currentTransform[0] + 20) + ",0)");
}
console.log(rec.attr("transform"))
function getTranslation(transform) {
if (transform === "") {
return [0, 0]
};
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
g.setAttributeNS(null, "transform", transform);
var matrix = g.transform.baseVal.consolidate().matrix;
return [matrix.e, matrix.f];
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>

Not able to add the fill between the paths. using d3js

i am trying to fill the background between 2 lines, but i am not getting any correct output.
and i would like to remove the tick line in the y axis as well. how to get this both?
here is my code : any one correct me please?
$(function(){
var m = [80, 80, 80, 80]; // margins
var w = 300; // width
var h = 450; // height
var plan = 55;
var actual = 38;
var variation = plan - actual;
var data = [0,plan];
var data1 = [0,actual];
var x = d3.scale.linear().domain([0, 2]).range([0, w]);
var y = d3.scale.linear().domain([0, 100]).range([h, 0]);
var line = d3.svg.line()
.x(function(d,i) {
return x(i);
})
.y(function(d) {
return y(d);
})
var graph = d3.select("#graph").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
var yAxisLeft = d3.svg.axis().scale(y).tickSize(-w).orient("left");
graph.append("svg:g")
.attr("class", "y axis")
.attr("transform", "translate(-0,0)")
.call(yAxisLeft);
graph.append("svg:path").attr("d", line(data));
graph.append("svg:path").attr("d", line(data1));
//not able to fill the bg between 2 lines
var area = d3.svg.area()
.x(function(d, i) { return 0 })
.x1(function(d, i) { return plan })
.y0(function(d, i) { return y(actual); })
.y1(function(d, i) { return y(variation); })
.interpolate("basis");
graph.append("path")
.datum(data)
.attr("d", area)
.attr("fill", "#CCC");
});
Live Demo
Concerning your area :
var area = d3.svg.area()
.x(function(d, i) { return 0 })
.x1(function(d, i) { return plan })
.y0(function(d, i) { return y(actual); })
.y1(function(d, i) { return y(variation); })
.interpolate("basis");
x and x1 are returning static values, so it won't draw an area but just a line
your both lines have same x axis so you just have to specify .x()
y0 and y1 are also returnin static values
Here is a working version :
var area = d3.svg.area()
.x(function(d, i) { return x(i) })
.y0(function(d, i) { return y(data[i]); })
.y1(function(d, i) { return y(data1[i]); })
Also be careful, you have a fill: none; in your css file so you won't see anything.
Functional plunker : http://plnkr.co/edit/xFNF3BQzd0IO5bauAiFU?p=preview

NVD3 Multi Bar Chart Labeling

I am trying to label multi bar chart. I am having issues with labeling. I hoping someone could help me.I am almost there, the labels are not aligned an i have no no idea why.
My chart is available here:
var chart_monthly;
var fundLabel_monthly;
var withSalesChargeFund_monthly;
var woutSalesChargeFund_monthly;
var indexPerformanceData_monthly;
var indexName_monthly;
var displaycase = true;
var yMin, yMax;
var width = 864;
var height = 380;
fundLabel_monthly = $("[id$='_hfAvgReturnFundLabel']").val(); // yields string, e.g. Genesis Fund, Class Trust - NBGEX
var keys = ['Class Trust', 'Class Institutional', 'Class Advisor', 'Class Investor', 'Class R3']
for (i = 0; i < keys.length; i++) {
var patt = new RegExp(keys[i]);
if (patt.test(fundLabel_monthly)) {
displaycase = false; // tells code to swap default to Without Sales Charge data set
break;
}
}
if (displaycase == false) {
$("[id$='monthly_saleschargetoggle']").hide();
withSalesChgFlag = false; //override what is passed in as for non A and C, there are no sales charges.
} else {
$("[id$='monthly_saleschargetoggle']").show();
}
indexName_monthly = $("[id$='_hfPrimaryBenchmarkName']").val();
if (indexName_monthly.length == 0 || indexName_monthly.length == 0)
return;
withSalesChargeFund_monthly = jQuery.parseJSON($("[id$='_hfWithSalesChargeFundMonthly']").val());
woutSalesChargeFund_monthly = jQuery.parseJSON($("[id$='_hfWoutSalesChargeFundMonthly']").val());
indexPerformanceData_monthly = jQuery.parseJSON($("[id$='_hfIndexPerformanceData']").val());
if (withSalesChargeFund_monthly.length == 0 || woutSalesChargeFund_monthly.length == 0 || indexPerformanceData_monthly.length == 0) {
return false;
}
var data = withSalesChgFlag ? getMonthlyDataWithSalesCharge() : getMonthlyDataWoutSalesChart();
nv.addGraph(function () {
chart_monthly = nv.models.multiBarChart()
.rotateLabels(0) //Angle to rotate x-axis labels.
.showControls(false) //Allow user to switch between 'Grouped' and 'Stacked' mode.
.groupSpacing(0.1) //Distance between each group of bars.
;
//create an array of all the y data points
var yArray = [];
for (i = 0; i < data[0].values.length; i++) {
yArray.push(data[0].values[i].y);
}
for (i = 0; i < data[1].values.length; i++) {
yArray.push(data[1].values[i].y);
}
var xArray = [];
for (i = 0; i < data[0].values.length; i++) {
xArray.push(data[0].values[i].x);
}
for (i = 0; i < data[1].values.length; i++) {
xArray.push(data[1].values[i].x);
}
yArray = yArray.sort(function(a,b){return a - b});
xArray = xArray.sort(function(a,b){return a - b});
yMax = d3.max(yArray);
yMin = d3.min(yArray);
yMax = Math.ceil(yMax+5);
yMin = Math.ceil(yMin-5);
var y = d3.scale.linear().range([height,0]).domain([yMin,yMax]);
var x = d3.scale.ordinal().rangeRoundBands([0, width], 0.1).domain(xArray);
chart_monthly.yAxis.showMaxMin(false);
chart_monthly.xAxis.tickFormat(function (d) {
var index = d.replace(/^\d+_/, '');
if (index < data[0].values.length) {
var label = data[0].values[index].label;
if (typeof label !== 'undefined') {
return label.replace(/(\d\d)(\d\d)$/, '$2').replace(/<br.+$/, '');
} else {
return '/';
}
} else {
return '-';
}
});
chart_monthly.yAxis.tickFormat(function (d) {
return d3.format(",.2f")(d) + '%';
});
chart_monthly.forceY([yMin, yMax]);
debugger;
d3.select('#nd3Chart')
.datum(data)
.call(chart_monthly);
var yTextPadding = 20;
d3.select('#nd3Chart .nv-series-0').selectAll("rect").select("text")
.data(data[0].values)
.enter()
.append("text")
.text(function(d,i) {
console.log(d.y)
if ( d.y == 0.00000001)
return "N/A";
else
return (d.y + "%");
})
.attr('x', function(d) {
//return (x(d.x)+15)
debugger;
console.log(x(i));
return x(i)+x.rangeBand();
}
)
.attr('y', function(d)
{
if (d.y<0)
return (y(d.y)+30);
else
return height-y(d.y)+yTextPadding;
//if (d.y<0)
// return (y(d.y)-30);
//else
// return (y(d.y)-15);
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "black")
.attr("text-anchor", "middle")
;
//////////////////////////////////////////////////
d3.select('#nd3Chart .nv-series-1').selectAll("rect").select("text")
.data(data[1].values)
.enter()
.append("text")
.text(function(d,i) {
console.log(d.y)
if ( d.y == 0.00000001)
return "N/A";
else
return (d.y + "%");
})
.attr('x', function(d,i) {
return x(i)+x.rangeBand()/2;
})
.attr('y', function(d, i)
{
if (d.y<0)
return (y(d.y)+30);
else
return height-y(d.y)+yTextPadding;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "black")
.attr("text-anchor", "middle")
;
nv.utils.windowResize(chart_monthly.update);
});
function getMonthlyDataWithSalesCharge() {
return [
{
"key": fundLabel_monthly,
"color": "#123a5f",
"values": withSalesChargeFund_monthly
},
{
"key": indexName_monthly,
"color": "#56a0d3",
"values": indexPerformanceData_monthly
}
];
}
function getMonthlyDataWoutSalesChart() {
return [
{
"key": fundLabel_monthly,
"color": "#123a5f",
"values": woutSalesChargeFund_monthly
},
{
"key": indexName_monthly,
"color": "#56a0d3",
"values": indexPerformanceData_monthly
}
];
}
Thanks
Alex

how to draw rectangles for each column in a row in d3.js

I would like to draw 4 different rectangles for each attribute in json. So i need to draw 4 rectangles for each id. in the below example i would have 16 rectangles for id 1-4.
The width, height of the rectangle are hard coded for now. Also the x and y axis.
Currently it takes each row as a rectangle.?
I have json data like this:
[
[{ "checkins":10},{"builds":11},{"oss":1},{"appsec":10},{"id":1}],
[{ "checkins":1},{"builds":1},{"oss":21},{"appsec":10},{"id":2}],
[{ "checkins":11},{"builds":3},{"oss":11},{"appsec":10},{"id":3}],
[{ "checkins":21},{"builds":20},{"oss":3},{"appsec":30},{"id":4}]
]
I have written the code:
var x_axis = 1;
var y_axis = 45;
var xvar;
var yvar;
var x;
d3.json("GraphData.json", function(data)
{
var rectangle= svggraph.selectAll("rect").data(data).enter().append("rect");
var RectangleAttrb = rectangle
.attr("id", function (d,i) { return "id" + i ; })
.attr("x", function (d,i)
{
xvar=i+1;
if(i==0) return x_axis=0;
if ((i > 0) && (xvar%4==1))
{
x_axis = 0;
}
else
{
x_axis=x_axis+22;
}
//y=i+1;
return x_axis;
})
.attr("y", function (d,i)
{
Yvar=i+1;
if ((i > 0) && (Yvar%4==1))
{
y_axis = y_axis+ 30;
}
return y_axis;
})
.attr("width",function(d) { return 20; } )
.attr("height",function(d) { return 15; })
.style("stroke", function (d) { return "black";})
.style("fill", function(d) { console.log(d);return "white"; });
});
It's still creating only 4 rectangles
I found a workaround solution. It was creating an array and looping through the same to create the rectangles and assigning the x and y axis along with the height and width.
<html>
<script>
var x_axis = 1;
var y_axis = 45;
var x;
var rectangle,RectangleAttrb;
var rect;
var rectdata;
createtinderboxes();
function createtinderboxes()
{
//console.log(" the function is called ");
d3.json("GraphData.json", function(data)
{
rectdata = data;
//console.log(rectdata.length);
for(x=0;x<rectdata.length;x++)
{
console.log(rectdata[x]);
for (index=0;index<5; index++)
{
svggraph.append("rect")
.attr("x", assignxaxis(rectdata, index))
.attr("y", assignyaxis(rectdata,yvar))
.attr("width", 20)
.attr("height", 25)
.style("fill","white")
.style("stroke","black");
}
yvar = yvar+26;
}
});
}
function assignxaxis(rectdata,x)
{
console.log(rectdata[x]);
if (x==4) return;
if(x==0)
{
return x_axis=0
}
else
{
x_axis=x_axis+22;
}
return x_axis;
}
function assignyaxis(rectdata,y)
{
return y;
}
</script>
</html>

Resources