Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs 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 its URL and the proper URL extension.

+ 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

Auto Save

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

              
                <div id='header'>
  <h1>U.S. Education Attainment</h1>
  <h2>
    Percentage of adults age 25 and older with a bachelor's degree or higher (2010-2014)
    <p class="hint">Mouseover or click a color in the Legend to view all counties of that color.</p>
  </h2>
</div>
<div id='svg-container'>
  <svg id='graph' width='1000' height='600'></svg>
  
</div>
              
            
!

CSS

              
                body{
  position: relative;
  font-family: 'Arial';
}
#header {
  position: relative;
  display: inline-block;
  text-align: center;
  left: 200px;
}
h1,
h2{
  display: block;
}
h1{
  font-size: 30px;
}
h2{
  font-size: 16px;
  font-weight: normal;
}


.hint {
  opacity: 0.6;
}

#svg-container {
  margin:0 50px;
  padding:0;
}

svg {
  display: block;
}
.county {
  transition: 1s;
  transform-origin: 50% 50%;
  opacity: 0.1;
}
.view{
  opacity: 1;
}

.states{
  transition: 1s;
  fill: none;
  transform-origin: 50% 50%;
  stroke: white;
}
.zoom {
  transform: scale(1.02);
}

.tooltip {
  position: absolute;
  background-color: rgba(255,255,255,0.9);
  text-align: center;
  color: black;
  pointer-events: none;
  border-radius: 5px;
  padding: 2px;
  p{
    display: block;
    margin: 0;
    padding: 0 5px;
    font-size: 12px;
  }
}

#legend > rect {
  transition: 500ms;
}
              
            
!

JS

              
                const GEO_DATA='https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json';
const EDUCATION_DATA='https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json';

const data={};
const themeHue=220;
var viewCategory=null;
//use promises to handle async fetch
function get(url){
  return new Promise(function(resolve,reject){
    var req=new XMLHttpRequest();
    req.open('GET',url);
    req.onload=function(){
      if(req.status==200){
        resolve(JSON.parse(req.response));
      }
      else {
        reject(Error(req.statusText));
      }
    };
    //handle network errors
    req.onerror=function(){
      reject(Error("Network Error"));
    }
    //make the request
    req.send();
  });
}
//run the function with promise chain
get(GEO_DATA)
  .then(response=>data.geo=response)
  .then(()=>get(EDUCATION_DATA))
  .then(response=>data.edu=response)
  .then(()=>build());

//begin drawing map
function build(){
  //variables,scales,functions
  const eduMin=d3.min(data.edu,(d)=>d.bachelorsOrHigher);
  const eduMax=d3.max(data.edu,(d)=>d.bachelorsOrHigher);
  const dataSteps=8;
  const lightMin=100;
  const lightMax=20;
  const lightStep=(lightMax-lightMin)/(dataSteps+1);
  const colorScale=d3.scaleThreshold()
    .domain(d3.range(eduMin,eduMax,(eduMax-eduMin)/dataSteps))
    .range(d3.range(lightMin,lightMax,lightStep));
  const colorHSL=(hue,light)=>{
    return 'hsl('+hue+',80%,'+light+'%)'
  }
  //identifiers
  let svg = d3.select('#graph');
  //debug
  console.log(data);
  //draw legend
  const legendX=605;
  const legendY=15;
  const legendH=10;
  const legendW=30;
  let legendScale=d3.scaleLinear()
    .domain([eduMin,eduMax])
    .range([0,legendW*colorScale.domain().length]);
  const legendAxis=d3.axisBottom(legendScale)
    .tickValues(colorScale.domain().concat(eduMax))
    .tickFormat((d)=>Math.round(d)+'%')
    .tickSize(10);
  const legend=svg.append('g')
    .attr('id','legend')
    .attr('transform','translate('+legendX+','+legendY+')');
  legend.selectAll('rect')
    .data(colorScale.domain())
    .enter()
    .append('rect')
    .attr('id',d=>'interval-'+Math.round(colorScale(d)))
    .attr('x',(d,i)=>i*legendW)
    .attr('y',legendY)
    .attr('width',legendW)
    .attr('height',legendH)
    .style('cursor','pointer')
    .style('fill',(d)=>colorHSL(themeHue,colorScale(d)))
    //click to freeze the map and view a specific category
    .on('click',(d)=>{
      if(viewCategory==d3.select('#interval-'+Math.round(colorScale(d))).attr('id').slice(9)) viewCategory=null;
      else if (!viewCategory) viewCategory = Math.round(colorScale(d));
    })
    .on('mouseenter',function(d){
      //freeze legend animations when viewing a category
      if(!viewCategory){
        d3.select(this)
          .attr('y',legendY-10)
          .attr('height',legendH+10);
        d3.selectAll('.states,.county-'+Math.round(colorScale(d)))
          .classed('zoom',true);
        d3.selectAll('.county:not(.county-'+Math.round(colorScale(d))+')')
          .classed('view',false);
      }
    })
    .on('mouseleave',function(d){
      //freeze legend animations when viewing a category
      if(!viewCategory){
        d3.select(this)
          .attr('y',legendY)
          .attr('height',legendH);
        d3.selectAll('.states,.county-'+Math.round(colorScale(d)))
          .classed('zoom',false);
        d3.selectAll('.county:not(.county-'+Math.round(colorScale(d))+')')
          .classed('view',true);
      }
    })
  legend.append('g')
    .attr('transform','translate(0,'+legendY+')')
    .call(legendAxis)
    .select('.domain').remove(); //removes the base line of the axis
  
  //draw map
  svg.append('g')
    .selectAll('path')
    //the dataset is already in topojson format, use topojson library
    .data(topojson.feature(data.geo,data.geo.objects.counties).features)
    .enter()
    .append('path')
    .attr('class',d=>'county view county-'+Math.round(colorScale(data.edu.filter(o=>o.fips==d.id)[0].bachelorsOrHigher)))
    .attr('data-fips',d=>d.id)
    .attr('data-education',d=>data.edu.filter(o=>o.fips==d.id)[0].bachelorsOrHigher)
    .style('fill',d=>colorHSL(themeHue,colorScale(data.edu.filter(o=>o.fips==d.id)[0].bachelorsOrHigher)))
    .attr('d',d3.geoPath())
    .on('mouseenter',function(d){
      //only allow tooltip and animation if area has .view class
      if (d3.select(this).attr('class').includes('view')){
        d3.select(this).style('stroke','black');
        //legend area effect on county hover
        d3.select('#interval-'+Math.round(colorScale(data.edu.filter(o=>o.fips==d.id)[0].bachelorsOrHigher)))
          .attr('y',legendY-10)
          .attr('height',legendH+10);
        //tooltip
        let tip=d3.select('#svg-container').append('div')
          .attr('id','tooltip')
          .attr('class','tooltip')
          .style('left',(d3.event.pageX-60)+'px')
          .style('top',(d3.event.pageY-60)+'px')
        tip.append('p')
          .html(data.edu.filter(o=>o.fips==d.id)[0].area_name + ', ' + data.edu.filter(o=>o.fips==d.id)[0].state);
        tip.append('p')
          .html(data.edu.filter(o=>o.fips==d.id)[0].bachelorsOrHigher + '%');
      }
    })
    .on('mouseleave',function(d){
      //only allow tooltip and animation if area has .view class
      if(d3.select(this).attr('class').includes('view')){
        d3.select(this).style('stroke','none');
        d3.selectAll('.tooltip').remove();
        //only animate legend if not viewing a category
        if(!viewCategory){
          d3.select('#interval-'+Math.round(colorScale(data.edu.filter(o=>o.fips==d.id)[0].bachelorsOrHigher)))
            .attr('y',legendY)
            .attr('height',legendH);
        }
      }
    })
  //draw states
  svg.append('path')
    .datum(topojson.mesh(data.geo,data.geo.objects.states),(a,b)=>a!==b)
    .attr('class','states')
    .attr('d',d3.geoPath());
  
}
              
            
!
999px

Console