What is the d3.js v4.0 equivalent for d3.scale.category10()? - d3.js

I'm trying to learn d3 with the Interactive Web Visualization book, but a lot has changed with version 4.0. One thing I really can't figure out is if there is an equivalent for d3.scale.category10() to get an easy mapping to colors. Is there something like that in the new version or do we need to use math.random and code up something ourselves?

Instead of
d3.scale.category10()
use
d3.scaleOrdinal(d3.schemeCategory10);
Create a color scale like this:
var color = d3.scaleOrdinal(d3.schemeCategory10);
use the color like this in the code same as in V3:
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100)
.style("fill", color(3))
read here
Reference here
working code here

A straight-forward solution is to use the following color scales in version-4 of d3.js :
var colorScale_1 = d3.schemeCategory10;
var colorScale_2 = schemeCategory20;
var colorScale_3 = d3.schemeCategory20b;
var colorScale_4 = d3.schemeCategory20c;
colorScale_1, colorScale_2, colorScale_3, colorScale_4 are the arrays of different colors. So, you can use their different indices to fill the shape. For example
svg.append("rect")
.attr("x", 10)
.attr("y", 10)
.attr("width", 100)
.attr("height", 100)
.style("fill", colorScale_1[2])
For reference, take a look here: http://bl.ocks.org/emmasaunders/f4902478bcfa411c77a412c02087bed4
Hope that helps.

Related

Putting tspan inside rectangle D3JS SVG

i'm working in projet of data visualization using D3JS.
i have to put some information inside a rectangle, and i did that using wrap function to split the content, no i'm looking to put each line (tspan) inside a rectangle. and i don't know how to do that, any help is appreciated for me.enter image description here
the small rectangles will contain informations. does any one have an example how to that. thakns
there!
Actually, what you need to do is set right position for groups.
var data = [0,1,2,3,4]; // example data
var selection = svg.selectAll('g').data(data).enter();
// set position for rects and texts using transform-translate
var groups = selection.append('g')
.attr('transform', function(d, i) { return 'translate(0,' + i * 35 + ')' });
groups.append('rect')
.attr('width', 100)
.attr('height', 30)
.attr('fill', 'white')
.attr('stroke', 'black'); // all rects
groups.append('text')
.text((d) => d)
.attr('font-size', '10px')
.attr('y', 15); // all texts
And an additional link for you, maybe it would be helpful.

Combining translate and rotate with D3

Quite possibly this repeats some of this SO question, but the code is overly-complicated and the OP hasn't added solution code. And this related question is no longer replicable.
I'm trying to figure out how to combine rotations and translations in the right order. It's possible to rotate around the origin as in this example. But when we follow this with a translation the original rotation is undone.
Is it possible to structure this for correct sequential application?
jsfidle code:
HTML:
<script src="http://d3.geotheory.co.uk/d3-transform.js"></script>
SVG:
var svg = d3.select("body").append("svg")
.attr("width", 400)
.attr("height", 300);
//Draw the Rectangle
var rect = svg.append("rect")
.attr("x", 0).attr("y", 0)
.attr("width", 50).attr("height", 100)
.style("fill", "purple");
var rotate = d3.svg.transform().rotate(-45);
var translate = d3.svg.transform().translate(200, 100);
rect.attr('transform', rotate);
var rect2 = rect.attr('transform', rotate);
rect2.attr('transform', translate);
If you're looking to do this in D3 version 4.x+ you can do it like so:
.attr('transform', 'translate(200,100)rotate(-45)')
https://bl.ocks.org/mbostock/1345853
You're creating two different transformations. Assigning one doesn't add to the other. That is, in doing
rect2.attr('transform', translate);
you're undoing the first one, as it is overwritten.
To have both, add them both to one transition, e.g.
var rotateTranslate = d3.svg.transform().rotate(-45).translate(200, 100);
rect2.attr('transform', rotateTranslate);
To do this dynamically, you'll need to do something like this.
.attr("transform", function() {
return d3.svg.transform()
.translate(200, 100)
.rotate(-45)
.translate(-d3.select(this).attr("width")/2, -d3.select(this).attr("height")/2)();
}
Complete jsfiddle here.

How to limit the text of polygons in Voronoi diagram with D3.js?

I've see the Example of D3.js-Voronoi Tessellation.But I want to put some text in each of polygons instead of a circle,Here is my js code:
var width = 600, height = 400;
var vertices = d3.range(20).map(function(d){
return [Math.random() * width, Math.random() * height]
});
var voronoi = d3.geom.voronoi();
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
path = svg.append("g").selectAll("path");
svg.selectAll("info")
.data(vertices.slice(1))
.enter().append("text")
.attr("transform", function(d) {
return "translate(" + d + ")";
})
.text("someText")
.attr("shape-rendering","crispEdges")
.style("text-anchor","middle");
redraw();
function redraw(){
path = path
.data(voronoi(vertices), polygon);
path.exit().remove();
path.enter().append("path")
.attr("class", function(d, i) {return "q" + (i % 9) + "-9";})
.attr("d", polygon);
path.order();
}
function polygon(d){
return "M" + d.join("L") + "Z";
}
I have a JSFiddle for that basic example here:
my voronoi code
now, I want each of the polygons' text in the center of the polygon, and don't cross with the polygon's border. If the polygon have not enough space to contain the all text, just contain the first part of it!
Let me know if there is anything I can do to solve this issue, thank you!
PS:I'm so sorry to my English, yes, it's so poor! :)
Have a look at this example http://bl.ocks.org/mbostock/6909318 , you probably want to place the text at the polygon centroid and not the seed (point) used to determine the voronoi tessellation.
That should fix the majority of your layout issues.
Automatically scaling the text to fit is a little bit harder, if you are willing to scale and rotate the text you can use a technique similar to the following to determine the length of the line at that point:
https://mathoverflow.net/questions/116418/find-longest-segment-through-centroid-of-2d-convex-polygon
Then you need to determine the angle of the line. I have a plugin that should help with that:
http://bl.ocks.org/stephen101/7640188/3ffe0c5dbb040f785b91687640a893bae07e36c3
Lastly you need to scale and rotate the text to fit. To determine the width of the text use getBBox() on the text element:
var text = svg.append("svg:text")
.attr("x", 480)
.attr("y", 250)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.style("font", "300 128px Helvetica Neue")
.text("Hello, getBBox!");
var bbox = text.node().getBBox();
Then you use the angle you calculated earlier to scale and rotate your text:
text.attr("transform", "rotate(40) scale(7)")
I would love to give a complete example but this is quite a bit of work to get it right.
There are other options to achieve the same effect but none of them are simple (ie you could anneal the layout similar to the way d3 does the Sankey layout)

Can I use images as the background rectangles for d3 treemaps?

Is it possible to make a treemap in d3 with the background of each rectangle be an image? I am looking for something similar to what was done in Silverlight here, but for d3. If it is possible, are there any recommended tutorials that walk through the process of connecting the background to an image?
Yes, there are several ways of using images in SVGs. You probably want to define the image as a pattern and then use it to fill the rectangle. For more information, see e.g. this question (the procedure is the same regardless of the element you want to fill).
In D3 code, it would look something like this (simplified).
svg.append("defs")
.append("pattern")
.attr("id", "bg")
.append("image")
.attr("xlink:href", "image.jpg");
svg.append("rect")
.attr("fill", "url(#bg)");
Its important to note, that the image needs to have width, height attributes
chart.append("defs")
.append('pattern')
.attr('id', 'locked2')
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', 4)
.attr('height', 4)
.append("image")
.attr("xlink:href", "locked.png")
.attr('width', 4)
.attr('height', 4);
Using patterns to add an image in a rectangle can make your visualisation quite slow.
You can do something like that instead, this is the code I used for my rectangular nodes into a force layout, I wanted to put rectangles filled by an image as nodes:
var node = svg.selectAll(".node")
.data(force.nodes())
.enter().append("g")
.attr("class", "node");
node.append("rect")
.attr("width", 80)
.attr("height", 120)
.attr("fill", 'none')
.attr("stroke", function (d) {
return colors(d.importance);
});
node.append("image")
.attr("xlink:href", function (d) { return d.cover;})
.attr("x", 2)
.attr("width", 76)
.attr("height", 120)
.on('dblclick', showInfo);

D3: How to access an attribute of a previous item

I am using D3 to plot a rectangle for each object in an array, the height of the rectangle being dependant on the 'Size' property of the object. These rectangles are stacked on top of each other. I currently set the y position by summing the 'Size' of each subsequent rect that gets plotted - but this seems wrong - and I was wondering if there was a better way to do this, such as accessing the 'y' attribute of the previous item (and how?) or another way...
This is what the essence of my code looks like. There is a link to the fiddle below.
var cumY = 0;
var blocks1 = sampleSVG.selectAll("rect")
.data(fpp)
.enter()
.append("rect")
.sort(SortBySize)
.style("stroke", "gray")
.style("opacity", blockOpacity)
.style("fill", function (d) {return d.Colour})
.attr("width", 80)
.attr("height", function (d) {return d.Size})
.attr("x", 5)
.attr("y", function (d, i) {
var thisY = cumY;
cumY += d.Size;
// perhaps I could just return something like d.Size + previousItem.GetAttribute("y") ???
return thisY;
});
http://jsfiddle.net/ninjaPixel/bvER3/
This is tricky do! You're right that keeping track of the cumulative height 'seems wrong' - it works now but it isn't very idiomatic d3 and will get pretty messy once you start trying to do something more complicated.
I would try using d3's built in stack-layout which was created solve this problem. You might want to start working off of this example and posting an updated fiddle if you get stuck. Good luck!

Resources