Hello,
I’m trying to finish the Treemap project but I’m having problems with the text labels.
I can’t wrap the SVG text. I know I should use tspans but I can’t really figure it out how.
Can somebody help?
//Declare VARIABLES
const w = 1000
const h = 600
const link = 'https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/movie-data.json'
var tooltip = d3
.select("body")
.append("div")
.attr('id', 'tooltip')
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.style('background-color', "lightgrey")
.style('border-radius', '12px')
.style('padding', '5px 10px')
.style('font-size', '12px')
//Declare SVG
const svg = d3
.select('body')
.append('svg')
.attr('width', w)
.attr('height', h)
d3.json(link)
.then(function(data){
var root = d3 .hierarchy(data)
.sum(d => d.value)
.sort((a, b) => b.value - a.value)
d3.treemap()
.size([w, h])
.paddingInner(1)
(root)
var keys = ['Action', 'Adventure', 'Comedy', 'Drama', 'Animation', 'Family', 'Biography']
// Color scale
var color = d3.scaleOrdinal()
.domain( keys )
.range([ "#4C92C3", "#BED2ED", "#FF993E", '#FFC993', '#56B356', '#ADE5A1', '#DE5253'])
// Opacity scale
var opacity = d3.scaleLinear()
.domain([ 10, 30 ])
.range([ 0, 1 ])
svg
.selectAll("rect")
.data(root.leaves())
.enter()
.append("rect")
.attr('x', d => d.x0 )
.attr('y', d => d.y0 )
.attr('width', d => d.x1 - d.x0 )
.attr('height', d => d.y1 - d.y0 )
.style("fill", d => color(d.parent.data.name) )
.style('opacity', d => opacity(d.data.value))
.on("mouseover", function(d){
return tooltip
.style("visibility", "visible")
.html('Name: ' + d.data.name + '<br/>' +
'Category: ' + d.data.category + '<br/>' +
'Value: ' + d.data.value
)
})
.on("mousemove", function(){
return tooltip
.style("top", (d3.event.pageY-10) +"px")
.style("left", (d3.event.pageX+10) +"px");
})
.on("mouseout", function(){
return tooltip
.style("visibility", "hidden")
})
svg
.selectAll("text")
.data(root.leaves())
.enter()
.append("text")
.attr("x", d => d.x0 )
.attr("y", d => d.y0 +10 )
.text(d => d.data.name )
.attr("font-size", "10px")
.attr("fill", "black")
})