Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"></script>
<h1>FCC Treemap Diagram Project</h1>
<select id="chooseDataType"></select>
<div class="svg-container-preload"></div>
<div class="svg-container"></div>
              
            
!

CSS

              
                /* ------------------- html-stuff ------------------ */
body {
  margin:0;
  padding:2rem 1rem 0 1rem;
}
h1{
  font-family:sans-serif;
  text-align:center;
  font-size:1.2rem;
  margin:0 0 1rem 0;
  padding:0;
}
.svg-container {
  max-width:1000px;
  margin: 0 auto;
  & > svg {
    border: 1px solid grey;
    font-family:sans-serif;
  }
}
#chooseDataType {
  margin:1rem auto;
  display:block;
  &:focus {outline:0;}
}
/* ------------------- svg-stuff ------------------ */
.show {
  visibility:visible;
}
.hide {
  visibility:hidden;
}
#tooltipContainer{
  text {fill:black;}
  rect {
    fill:white;
    stroke:black;
    stroke-width:0.3;
  }
}
              
            
!

JS

              
                // fcc: https://learn.freecodecamp.org/data-visualization/data-visualization-projects/visualize-data-with-a-treemap-diagram
// example: https://codepen.io/freeCodeCamp/full/KaNGNR

// wiki: https://en.wikipedia.org/wiki/Treemapping
// - hierarchical-data: each branch as a rectangle;
// - it is then tiled with smaller rectangles (sub-branches)
// - node's rectangle has an area proportional to a specified dimension of the data
// - six primary rectangular treemap algorithms

// d3.js: https://www.d3-graph-gallery.com/treemap
// - maps can be made zoomable to dig into the branches
// -> https://www.d3-graph-gallery.com/graph/treemap_json.html

// multi-select
// allows: .attrs({foo:42, goo:23})
// https://d3js.org/d3-selection-multi.v1.min.js

let cl = console.log;

// =================== config =================
// global lookup for values
const lookup = (function(){
  // private vars
  const range = [[0,100],[0,65]];
  const spaces = [14,3,30,3]; // trbl
  const basePath = 'https://cdn.rawgit.com/freeCodeCamp/testable-projects-fcc/a80ce8f9/src/data/tree_map/';
  const dataUrls = [basePath+'kickstarter-funding-data.json', basePath+'movie-data.json', basePath+'video-game-sales-data.json'];
  const idsTitle ={outer:'titleContainer', txt:'title'};
  const idsDescription ={outer:'descriptionContainer', txt:'description'};  
  const idsTooltip ={outer:'tooltipContainer', txt:'tooltip', box:'tooltipBox'};
  const titles = ['Kickstarter Pledges','Movie Sales','Video Game Sales'];
  const subTitles = ['Top 100 Most Pledged Kickstarter Campaigns Grouped By Category','Top 100 Highest Grossing Movies Grouped By Genre','Top 100 Most Sold Video Games Grouped by Platform'];
  const legend = {lWidth:3, lHeight:3, lRowLength:4, lTextWidth:20, yOff:1, yStartOff: 2};
  const legendColors = ['#e6194b', '#3cb44b', '#ffe119', '#4363d8', '#f58231', '#911eb4', '#46f0f0', '#f032e6', '#bcf60c', '#fabebe', '#008080', '#e6beff', '#9a6324', '#fffac8', '#8aaaaa', '#aaffc3', '#808000', '#ffd8b1', '#aaaa75', '#808080',  '#000000'];
  
  // public methods
  return Object.freeze({ // no modificaton of method-definition
    getUrls: function(){return dataUrls;},
    getTitles: function(){return titles;},
    getSubTitles: function(){return subTitles;},
    getIdsTitle: function(){return idsTitle;},
    getIdsDescription: function(){return idsDescription;},
    getIdsTooltip: function(){return idsTooltip;},
    getRange: function(){return range;},
    getSpaces: function(){return spaces;},
    getLegend: function(){return legend;},
    getLegendColors: function(){return legendColors;}
  })
})();


// =============== d3-helper ==============
function getSvg(selector) {
  d3.select(selector+' svg').remove();
  return d3.select(selector).append("svg");
} 

function addViewBox(svg, range, spaces) {
  svg.attr('viewBox',
    (-spaces[3] + Math.min(...range[0]))
    +' '+ (-spaces[0]+Math.min(...range[1]))
    +' '+ (spaces[1] + spaces[3] + Math.abs(range[0][1]-range[0][0]))
    +' '+ (spaces[2] + spaces[0] + Math.abs(range[1][1]-range[1][0]))
  ); 
}

// text: fix markup
function addText(svg, ids) {
  const outer = svg.append('svg').attr('id',ids.outer).attr('class','hide');
  const txt = outer.append('text').attr('id', ids.txt)
  if(ids.box !== undefined) {outer.append('rect').attr('id',ids.box).lower();}
}

// text: dynamic markup
// position: l|c|r
function setText(ids, text, x, y, fontSize=4, spaceLR=5, spaceTB=4, position='c') {
  const txt =  d3.select('#'+ids.txt);
  txt.text(text).attr('x', spaceLR/2).attr('y', fontSize+spaceTB/4).attr('font-size', fontSize);
  let w = txt.node().getComputedTextLength()+spaceLR;
  
  var adjX = -w/2; // center
  if(position=='l') adjX = 0; // left
  if(position=='r') adjX = -w; // right
  
  const outer = d3.select('#'+ids.outer);
  outer.attr('x', x+adjX).attr('y', y).attr('class','show');
  
  if(ids.box !== undefined) {
    const box = d3.select('#'+ids.box);
    box.attr('width', w).attr('height', fontSize+spaceTB);    
  }
}

// special treemap multiline solution
function setMultiTextBox(id, arrText, x, y, fontSize, maxX, maxY) {
  const spaceLR = 0.7;
  const objText =  d3.select('#'+id);
  maxX -= spaceLR;
  let innerX = x+spaceLR/2;
  let widths = [], h=0, ts, ts2, dy = fontSize;

  // [1] enough room for text
  arrText.forEach((v,i)=>{
     ts=objText.append('tspan').text(v).attr('x',innerX).attr('dy',dy);  
     ts.attr('font-size', fontSize);
     widths.push(ts.node().getComputedTextLength());
     h+=dy;
  });   
  let w = Math.max(...widths);
  let densitiy = arrText[0].length/widths[0];
  
  // [2] NOT enough room for text
  if(w>maxX || h>maxY) {
      let text = arrText.join(' '); // single line
      objText.selectAll('*').remove(); // remove text from [1]
      text=text.substr(0,Math.max(1, maxX*densitiy-3)); // first letters only
      ts=objText.append('tspan').text(text).attr('x',innerX).attr('dy',dy);
      objText.append('tspan').attr('font-size', fontSize).text('…');  
      ts.attr('font-size', fontSize);
  }
}

// simple multiline solution
function setMultiText(ids, arrText, x, y, fontSize=4, position='l', max=60) {
  const spaceTB = 2, spaceLR = 2;
  const objText =  d3.select('#'+ids.txt);
  objText.selectAll('*').remove(); // remove 'old' children
  
  let widths = [],
      ts, ts2,
      dy = fontSize+1
  
  arrText.forEach((v,i)=>{
    let c=v;
    if(v.length>max) {
      c=v.substr(0,max-3); 
      ts=objText.append('tspan').text(c).attr('x',spaceLR/2).attr('dy',dy);
      objText.append('tspan').attr('font-size', fontSize).text('...').attr('class', 'points-3').append('title').text(v);  
    } else {
      ts=objText.append('tspan').text(c).attr('x',spaceLR/2).attr('dy',dy);   
    }
    ts.attr('font-size', fontSize);
    widths.push(ts.node().getComputedTextLength());
  });  
 
  let w = Math.max(...widths);
  const minWidth = 35;
  if(w<minWidth) w=minWidth;
  var adjX = -w/2; // center
  if(position=='l') adjX = 0; // left
  if(position=='r') adjX = -w; // right
  
  const outer = d3.select('#'+ids.outer);
  outer.attr('x', x+adjX).attr('y', y).attr('class','show');
  
  if(ids.box !== undefined) {
    const box = d3.select('#'+ids.box);
    box.attr('width', w+spaceLR).attr('height', arrText.length*dy+spaceTB);
  }
}


// helper-class
class Scales {
  constructor(data, range) {
    this.data=data;  
    this.range=range;
    this.rangeHalfX = (this.range[0][1]-this.range[0][0])/2;
    this.px = this.percent(range[0]); // percent-scales within range
  }

  percent(arrMinMax) {
    const scaleP = d3.scaleLinear();
    scaleP.domain([0,100]);
    scaleP.range(arrMinMax);
    return scaleP;
  }
} // Scales

function createTextArray(txt) {
   return txt // create arr: split by every 2nd space
          .replace(' - ','-').replace(', ',',') // ignore: - and ,
          .split(' ')
          .reduce((acc,v,i,a)=>{
            if(i%2==1) acc.push((a[i-1]+' '+a[i]).replace('-',' - ').replace(',',', '));
            else if(i==a.length-1) acc.push(a[i])
            return acc;
        }, []);
}


// ================ d3-svg ==================
// load-info
function showLoader(selector, range) {
  const svg = getSvg(selector);
  addViewBox(svg, range, [0,0,0,0]);
  svg.append('text').attr('id','preload').text('loading').attr('text-anchor','middle').attr('x',50).attr('y',25).attr('fill', 'grey').attr('font-size',10);   
}

// display graph
function showData(payload) {
  let {data, dataType, selector, selectorPreload, range, spaces}=payload;
  let {lWidth, lHeight, lRowLength, lTextWidth, yOff, yStartOff} = lookup.getLegend();
  
  document.querySelector(selectorPreload).style.display = 'none';
  document.querySelector(selector).style.display='block';
 
    // ------------- treemap-data -----------
  // - size of each leave is given in the 'value' field
  // - {children: [{child1, child2, {other children-object}}, {...}]}
  var root = d3.hierarchy(data).sum(function(d){ return d.value});
  d3.treemap()
    .size([range[0][1], range[1][1]])
    .padding(0) // space between branch-boxes; test fails if > 0
    (root);
  
  // category-colors
  let catColorsArr = []; // for: legend
  const cols = lookup.getLegendColors();
  let catColors = root.children.reduce((acc,v,i,a)=>{
    if(a.length>=cols.length) {
      const v1 = (i/a.length*0.8+0.2), v2 = v1*255;
      const c = 'rgba('+v2+','+v2+',0,'+v1+')';
      acc[v.data.name]=c;    
      catColorsArr.push({name:v.data.name, color:c});
    } else {
      acc[v.data.name]=cols[i];
      catColorsArr.push({name:v.data.name, color:cols[i]});
    }
    return acc;
  },{});
  
  // adjust spaces-bottom with legend-height
  const legendHeight = Math.round(catColorsArr.length/lRowLength)*(lHeight+yOff)+yStartOff;
  spaces[2] = legendHeight; 
  
  const svg = getSvg(selector);
  addViewBox(svg, range, spaces);
  
  let scale = new Scales(data, range);
 
  // ------------- titles -------------
  addText(svg, lookup.getIdsTitle());
  setText(lookup.getIdsTitle(), lookup.getTitles()[dataType], scale.px(50), -15, 5, 2, 3);
  
  addText(svg, lookup.getIdsDescription());
  setText(lookup.getIdsDescription(), lookup.getSubTitles()[dataType], scale.px(50), -7, 2.5, 2, 3);
  

  // ------------- treemap -----------
  const leaves = root.leaves();
  const container = svg.append('g');
  container
    .selectAll("rect")
    .data(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)
      .attr('class','tile')
      .attr('data-name', d=>d.data.name)
      .attr('data-category', d=>d.data.category)
      .attr('data-value', d=>d.data.value)
      .attr("stroke", "black")
      .attr("stroke-width", "0.2")
      .attr("fill", d=>catColors[d.data.category])
      .on('mousemove', function(d,i){
        let arrText = createTextArray("Name: " + d.data.name);
        arrText = arrText.concat(["Category: "+d.data.category, "Value: "+d.data.value]);
        const x = d3.mouse(this)[0];
        let adj  = {'l':1.0, 'r':-2.5};
        let pos = 'l';
        if(x>scale.rangeHalfX) pos = 'r';
        setMultiText(lookup.getIdsTooltip(), arrText, x, d3.mouse(this)[1]+1.5, 2.5, pos);
        d3.select('#'+lookup.getIdsTooltip().txt).attr('data-value', d.data.value);
      })
      .on('mouseout', function(d,i){
        d3.select('#'+lookup.getIdsTooltip().outer).attr('class','hide');  
      })  
      //.append('title')
    	//.text(d=>d.data.name)
    
  container
    .selectAll("text")
    .data(leaves)
    .enter()
    .append("text")
      .attr("x", d=>d.x0)
      .attr("y", d=>d.y0)
      .attr("fill", "black")
      .attr("id", (d,i)=>'text'+i)
      .attr("data-name", (d,i)=>{
        const id = 'text'+i;
        const txt = createTextArray(d.data.name);
        setMultiTextBox(id, txt, d.x0, d.y0, 1, d.x1 - d.x0, d.y1 - d.y0);
        return d.data.name;
      })
  
  // --------------- legend --------------
  // testing: multi-select with attrs()
  const legend = svg.append('g').attr('id','legend');
  const rectObj = {
    class: 'legend-item',
    x: (d,i)=>(i%lRowLength)*(lWidth+lTextWidth),
    y: (d,i)=>Math.floor(i/lRowLength)*(lHeight+yOff)+yStartOff+range[1][1],
    width: lWidth,
    height: lHeight,
    fill: d=>d.color
  };

  const textObj = {
    class: 'legend-text',
    x: (d,i)=>(i%lRowLength)*(lWidth+lTextWidth)+lWidth+0.5,
    y: (d,i)=>Math.floor(i/lRowLength)*(lHeight+yOff)+lHeight*0.7+yStartOff+range[1][1],
    fill: 'black',
    'font-size':lHeight*0.4
  };
  
  legend
    .selectAll('rect')
    .data(catColorsArr)
    .enter()
    .append('rect')
      .attrs(rectObj)
      .append('title').text(d=>d.name)
  legend
    .selectAll('text')
    .data(catColorsArr)
    .enter()
    .append('text')
      .attrs(textObj)
      .text(d=>d.name);
  
  // ---- add tooltip -------------
  addText(svg, lookup.getIdsTooltip());
} // showData

function loadData(dataType) {
  document.getElementsByClassName('svg-container-preload')[0].style.display='block';
  document.getElementsByClassName('svg-container')[0].style.display='none';
  showLoader('.svg-container-preload', lookup.getRange()); // preload-info  
  
  d3.json(lookup.getUrls()[dataType]).then(
    (dataset)=>showData({data:dataset, dataType:dataType, selector:'.svg-container',selectorPreload:'.svg-container-preload', range:lookup.getRange(), spaces:lookup.getSpaces()})
  ).catch(function(error){console.log(error.message)});
}

// ================== main ==================
const sel = document.getElementById('chooseDataType');
lookup.getTitles().forEach((v,i)=>{
  const opt = document.createElement("option");
  opt.text=v;
  opt.value=i;
  sel.add(opt);
});
sel.onchange = function(){loadData(this.value);};

loadData(0);
              
            
!
999px

Console