D3 wrapping text legends - javascript

I am using legends for d3 charts. Below is code -
var padding = { left:50, right:100, top:30, bottom:30 };
var legend = svgColorCode.selectAll(".legend")
.data(keyText) //.filter(x=>x!="Completed On Time")
.enter().append("g")
.attr("class", "legend")
.attr("transform", function (d, i) { return "translate(" + (((keys.length - (i)) * -25) + (i == 0 ? 0 : (i == 1 ? 60 : (i == 2 ? 90 : (i == 3 ? 100 : 0))))) + "," + (height - 190) + ")"; })
.attr("fill", function (d, i) { return colors[i]; });
legend.append("rect")
.attr("x", (x, i) => (padding.top * 2 + labHeight * (i)) + 40)
.attr("width", 18)
.attr("height", 18)
.style("fill", function (d, i) { return colors[operationalKeys[i]]; })
legend.append("text")
.attr("x", (x, i) => (padding.top * 2 + labHeight * i) + 60)
.attr("y", 9)
.attr("font-size", "0.65rem")
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function (d) { console.log("d");console.log(d); return d.replace("&nbsp","\n"); })
.call(wrap)
;
Here I have long texts for legends and small place to accomodate it. I want to wrap the text for legends.
For that I followed this SO answer and used wrap method. But seems wrap is not working in this case.
How can I wrap my text for legends in d3 js?

Related

How to set symbols in a legend?

I'm newbie in D3 and I'm trying to set a symbol on the left of the text of a legend. The legend is on the right of the graphic and all the texts of the legend are correctly located but I cannot be able to located on their left the symbol which corresponds with the legend.
The function which locate the legend and try to do the same with the symbols are:
setLegend(canvas, symbols, width, offset_right, height) {
canvas
.selectAll("legends")
.data(symbols)
.enter()
.append("text")
.attr("transform", function(d, i) {
let x = width - offset_right + 50;
let y = height / 2 - 100 + i * 24;
return "translate( " + x + "," + y + ")";
})
.attr(
"d",
d3
.symbol()
.type(function(d) {
return d.symbol;
})
.size("75")
)
.style("text-anchor", "left")
.text(d => {
return d.stats;
})
.attr("fill", "#FFFFFF")
.style("font-size", "10pt")
.style("font-weight", "bold"); }
You can check in this screen cap how the legend is correctly located but there are no any symbol on its left.
You can check all the code of the development in codesanbox:
What am I doing wrong?
Right now you're setting an attribute called d to text elements, which has no effect on those texts (only paths have the d attribute). On top of that, you're not appending any path.
A simple and common fix is appending groups in the enter selection, to which you append the paths and texts. Here is an example (I'm setting the x and y positions of the texts so they don't start right over the symbols):
setLegend(canvas, symbols, width, offset_right, height) {
const groups = canvas
.selectAll("legends")
.data(symbols)
.enter()
.append("g")
.attr("transform", function(d, i) {
let x = width - offset_right + 50;
let y = height / 2 - 100 + i * 24;
return "translate( " + x + "," + y + ")";
});
groups.append("path")
.attr("d", d3.symbol().type(function(d) {
return d.symbol;
}).size("75"))
.attr("fill", function(d) {
return d.color;
});
groups.append("text")
.attr("x", 10)
.attr("y", 5)
.style("text-anchor", "left")
.text(d => {
return d.stats;
})
.attr("fill", function(d) {
return d.color;
})
.style("font-size", "10pt")
.style("font-weight", "bold");
}

d3 clock text upside down

How can I have all numbers from 13 - 11 not rotated? (I'd like all of them be displayed in current positions, but without rotating them - as here: http://bl.ocks.org/tomgp/6475678)
This is my code right now:
var xTick = xAxis
// .selectAll("g")
.selectAll(".radial")
.data(x.ticks(24))
.enter().append("g")
.attr("text-anchor", "middle")
.attr("transform", function(d) {
return "rotate(" + ((x(d)) * 180 / Math.PI - 90) + ")translate(" + innerRadius + ",0)";
});
xTick.append("line")
.attr("x2", -5)
.attr("stroke", "#595D5C");
xTick.append("text")
.attr("transform", function(d) {
var angle = x(d.key);
return ((angle < Math.PI / 2) || (angle > (Math.PI * 3 / 2))) ? "rotate(90)translate(0,0)" : "rotate(-90)translate(0, -15)"; })
.text(function(d) {
return d;
})
.style("font-size", 10)
.attr("color", "#595D5C")
.attr("opacity", 1)

Need to have only integers in x-axis - d3

I am facing issue in order to have integer values in x-axis(graph shown in above link). x-axis should be divided as 1,2,3 but it is getting divided as 0.0, 0.2, 0.4, 0.6,...,2.8 ,3.0 .
I have the following code:
private initSvg() {
d3.select("#svg1")
.attr("width", document.getElementById("svg1").parentElement.offsetWidth - 300 - this.margin.left - this.margin.right)
.attr("height", (document.getElementById("svg1").parentElement.offsetWidth / 3))
this.svg = d3.select('#svg1');
this.width = document.getElementById("svg1").parentElement.offsetWidth - 300 - this.margin.left - this.margin.right;
// this.height = +this.svg.attr("height") - this.margin.top - this.margin.bottom;
this.height = (document.getElementById("svg1").parentElement.offsetHeight - 100)
// console.log(this.width, this.height)
this.g = this.svg.append("g")
.attr("transform", "translate(" + (this.margin.left + 100) + "," + this.margin.top + ")");
}
private initAxis() {
this.y = d3Scale.scaleBand().rangeRound([0, this.height]).padding(0.1);
this.x = d3Scale.scaleLinear().rangeRound([this.width, 0]);
this.y.domain(this.STATISTICS.map((d) => d.qua));
this.x.domain([d3Array.max(this.STATISTICS, (d) => d.value + 2), 0]);
}
private drawAxis() {
this.g.append("g")
.attr("class", "x")
.attr("transform", "translate(0," + this.height + ")")
.call(d3Axis.axisBottom(this.x).tickSize(-this.height))
.selectAll("text")
.attr("dy", "1em")
.selectAll("path")
.attr("class", "opac")
.style("stroke-opacity", "0")
this.g.append("g")
.attr("class", "y")
// .attr("transform", "translate(0," + (- ((document.getElementById("svg1").parentElement.offsetWidth / 3) * 10) / 100) + ")")
.call(d3Axis.axisLeft(this.y).tickSize(-this.width))
.append("text")
.attr("class", "axis-title")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
}
private drawBars() {
var i = 0;
var trans = this.g.selectAll(".bar")
.data(this.STATISTICS)
.enter().append("rect")
.style("fill", (d: any) => { i++; return this.colorrange[i]; })
.attr("y", (d) => this.y(d.qua))
.attr("height", (this.y.bandwidth()))
// .attr("height", 60)
trans.transition()
.duration(2000)
.delay(function (d, i) {
return i * 50;
})
.attr("x", (d) => 0 /*this.x(d.AverageValue)*/)
.attr("width", (d) => /* this.height -*/ this.x((d.value == "" ? 0 : d.value)))
}
private drawLabel() {
this.g.selectAll('.label')
.data(this.STATISTICS)
.enter().append('text')
.attr('class', (d) => this.x(d.value) < 50 ? 'label bar-value-2' : 'label bar-value')
.style('font-size', (d) => (this.y.bandwidth() < 30 ? this.y.bandwidth() * 0.7 : 14) + 'px')
// .attr('x', (d) => this.x(d.AverageValue) < 40 ? 40 : this.x(d.AverageValue) - 7)
.attr('x', 100)
.attr('y', (d) => this.y(d.qua) + this.y.bandwidth() * 0.5 + 6);
}
And I am calling all this in a different method to get result:
setTimeout(() => {
this.initSvg()
this.initAxis()
this.drawAxis()
this.drawBars()
this.drawLabel()
}, 500);
Note:
STATISTICS = [
{qua: "Yes", value: 1}
{qua: "No", value: 1},
];
Tried to change something in x-domain but it didn't worked. Honestly, I am new to d3 and that's why don't know where to make changes.
Need further assistance.
Thanks.

D3.js Day Hour Heatmap dynamic update

I'm very new to D3.js and I'm trying to learn how to put things together correctly. I have a day/hour heatmap based on this example here: http://bl.ocks.org/tjdecke/5558084
I'm trying to write an updateHeatMap method so that I can dynamically update the heatmap with new data. I've been researching and researching, and I honestly haven't found a successful solution. Any help would be appreciated, code snippets below
I have changed the original day/hour heatmap example slightly to look like this:
$scope.heatMapData = $http.get(...
$scope.initHeatMap = function() {
var margin = { top: 50, right: 0, bottom: 100, left: 30 },
width = 960 - margin.left - margin.right,
height = 430 - margin.top - margin.bottom,
gridSize = Math.floor(width / 24),
legendElementWidth = gridSize*2,
buckets = 9,
colors = ["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb","#41b6c4","#1d91c0","#225ea8","#253494","#081d58"], // alternatively colorbrewer.YlGnBu[9]
days = ["Mo", "Tu", "We", "Th", "Fr", "Sa", "Su"],
times = ["1a", "2a", "3a", "4a", "5a", "6a", "7a", "8a", "9a", "10a", "11a", "12a", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "10p", "11p", "12p"];
$scope.colorScale = d3.scale.quantile()
.domain([0, buckets - 1, d3.max($scope.heatMapData, function (d) { return d.value; })])
.range(colors);
var svg = d3.select("#chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var dayLabels = svg.selectAll(".dayLabel")
.data(days)
.enter().append("text")
.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) { return i * gridSize; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize / 1.5 + ")")
.attr("class", function (d, i) { return ((i >= 0 && i <= 4) ? "dayLabel mono axis axis-workweek" : "dayLabel mono axis"); });
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter().append("text")
.text(function(d) { return d; })
.attr("x", function(d, i) { return i * gridSize; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + gridSize / 2 + ", -6)")
.attr("class", function(d, i) { return ((i >= 7 && i <= 16) ? "timeLabel mono axis axis-worktime" : "timeLabel mono axis"); });
var heatMap = svg.selectAll(".hour")
.data($scope.heatMapData)
.enter().append("rect")
.attr("x", function(d) { return (d.hour - 1) * gridSize; })
.attr("y", function(d) { return (d.day - 1) * gridSize; })
.attr("rx", 4)
.attr("ry", 4)
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", colors[0]);
heatMap.transition().duration(1000)
.style("fill", function(d) { return $scope.colorScale(d.value); });
heatMap.append("title").text(function(d) { return d.value; });
var legend = svg.selectAll(".legend")
.data([0].concat($scope.colorScale.quantiles()), function(d) { return d; })
.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height)
.attr("width", legendElementWidth)
.attr("height", gridSize / 2)
.style("fill", function(d, i) { return colors[i]; });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d); })
.attr("x", function(d, i) { return legendElementWidth * i; })
.attr("y", height + gridSize);
};
Here is what I have so far with the update method. This isn't working, because I'm not sure how to get the updated $scope.heatMapData into the new heatMap variable. I also need to update the legend to match the new color scale, but that's second in priority under this.
$scope.rowSelected() = function(){
$http.get(...).then(function(result){
$scope.heatMapData = result.data;
$scope.updateHeatMap();
});
}
$scope.updateHeatMap = function(){
var svg = d3.select("body").transition();
var heatMap = svg.selectAll(".hour")
.duration(250)
.attr("x", function(d) { return (d.hour - 1) * gridSize; })
.attr("y", function(d) { return (d.day - 1) * gridSize; })
.attr("rx", 4)
.attr("ry", 4)
.attr("class", "hour bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.style("fill", colors[0]);
heatMap.transition().duration(1000)
.style("fill", function(d) { return colorScale(d.value); });
}

Add image to D3.js Sunburst Example

I would like to extend this D3.js sunburst example in the way that it can display images rather than text. http://www.jasondavies.com/coffee-wheel/
The interesting part of the js example code is following:
d3.json("wheel.json", function(error, json) {
var nodes = partition.nodes({children: json});
var path = vis.selectAll("path").data(nodes);
path.enter().append("path")
.attr("id", function(d, i) { return "path-" + i; })
.attr("d", arc)
.attr("fill-rule", "evenodd")
.style("fill", colour)
.on("click", click);
var text = vis.selectAll("text").data(nodes);
var textEnter = text.enter().append("text")
.style("fill-opacity", 1)
.style("fill", function(d) {
return brightness(d3.rgb(colour(d))) < 125 ? "#eee" : "#000";
})
.attr("text-anchor", function(d) {
return x(d.x + d.dx / 2) > Math.PI ? "end" : "start";
})
.attr("dy", ".2em")
.attr("transform", function(d) {
var multiline = (d.name || "").split(" ").length > 1,
angle = x(d.x + d.dx / 2) * 180 / Math.PI - 90,
rotate = angle + (multiline ? -.5 : 0);
return "rotate(" + rotate + ")translate(" + (y(d.y) + padding) + ")rotate(" + (angle > 90 ? -180 : 0) + ")";
})
.on("click", click);
textEnter.append("tspan")
.attr("x", 0)
.text(function(d) { return d.depth ? d.name.split(" ")[0] : ""; });
textEnter.append("tspan")
.attr("x", 0)
.attr("dy", "1em")
.text(function(d) { return d.depth ? d.name.split(" ")[1] || "" : ""; });
The question is how I can replace the text with an image in this scenario.
Thank you very much.
var image = vis.selectAll("image").data(nodes);
var imageEnter = image.enter().append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("width", 16)
.attr("height", 16)
.attr("x", function (d) {
return 33; // calculate x
}).attr("y", function (d) {
return 33; // calculate y
});
https://developer.mozilla.org/en-US/docs/Web/SVG/Element/image
force-directed images and labels: http://bl.ocks.org/mbostock/950642

Categories

Resources