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. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

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

              
                <div class="graph">
</div>
<div id="tooltip" class="hidden">
  <h3 id="tooltip-title"></h3>
  <div class="inner-cont">
    <div id="tooltip-graph"></div>
    <p id="tooltip-data"></p>
  </div>
</div>
              
            
!

CSS

              
                $colorFemale: #FF1493
$colorATQ: #FFFF00
$colorMale: #000080
$colorWater: #add8e6
$colorNoData: #fff

body
  display: flex
  justify-content: center
  font-family: 'arial', sans-serif
#tooltip
  position: absolute
  visibility: visible
  opacity: 1
  transition: visibility 0s, opacity 0.3s linear
  background-color: rgba(255,255,255,0.8)
  color: black
  padding: 0 15px 15px
  border-radius: 5px
  max-width: 400px
  &.hidden
    visibility: hidden
    opacity: 0
    transition: visibility 0s, opacity 0.3s linear
  .inner-cont
    display: flex
    
  #tooltip-graph
    margin-right: 10px
  #tooltip-data
    p, ul
      margin: -1em 0!important
    ul
      list-style: square
      background-color: rgba(0,0,0,0.8)
      padding: 10px 10px 10px 30px
      border-radius: 3px
      li
        margin-bottom: 0.3em
      span
        color: white
    li.ATQ
      color: $colorATQ
    li.female
      color: $colorFemale
    li.male
      color: $colorMale
    li.NR
      color: $colorNoData
    
.overlay
  fill: none
  pointer-events: all
              
            
!

JS

              
                var surveyData = 'https://raw.githubusercontent.com/FreeCodeCamp/2016-new-coder-survey/master/data/2016%20New%20Coders%20Part%202.csv';
var worldJSON = 'https://raw.githubusercontent.com/krisgesling/d3-play/master/world-geo2-min.json';
var graphData = {};
var width = 1000;
var height = width/6*4;
countryField = "Which country are you a citizen of?";
genderField = "What's your gender?";

// Color assignment - remember to also change sass variables
var colorFemale = '#FF1493';
var colorATQ = '#FFFF00';
var colorMale = '#000080';
var colorWater = '#add8e6';
var colorNoData = '#fff';
var pieColor = [colorATQ,colorFemale,colorMale,colorNoData];
var colorLand = ['#f0f7da','#c9df8a','#77ab59','#36802d','#234d20'];


function loadData(data) {
    // Country constructor
    function Country(female,ATQ,male,NR,displayName) {
      this.female = female;
      this.ATQ = ATQ;
      this.male = male;
      this.NR = NR;
      this.displayName = displayName;
    }
    
    function countGenderByCountry(e,i,arr) {
      // Remove white spaces from Country names - required to match with worldJSON data
      var countryLookup = {
        'Bosnia & Herzegovina': 'Bosnia and Herzegovina',
        'Korea South': 'South Korea',
        'Korea North': 'North Korea',
        'Netherlands (Holland, Europe)': 'Netherlands',
        'Congo': 'Democratic Republic of the Congo',
        'Tanzania': 'United Republic of Tanzania',
        'Nambia': 'Namibia',
        'Cote D\'Ivoire': 'Ivory Coast',
        'Republic of Montenegro': 'Montenegro'
      };
      var countryNameDisplay = countryLookup[data[i][countryField]] ? countryLookup[data[i][countryField]] : data[i][countryField];
      var countryName = countryNameDisplay.replace(/\s/g, '');
      // Create new country object if not already present in graphData
      if (!graphData[countryName]) {
        graphData[countryName] = new Country(0,0,0,0,countryNameDisplay);
      }
      // Increment relevant field
      switch (data[i][genderField]) {
        case 'female':
          graphData[countryName].female ++;
          break;
        case 'male':
          graphData[countryName].male ++;
          break;
        case 'trans':
        case 'agender':
        case 'genderqueer':
          graphData[countryName].NR ++;
          break;
        default:
          graphData[countryName].NR ++;
      }
    }
  
    data.forEach(countGenderByCountry);
    // Calculate non-male:male gender ratio for each country
    for (var key in graphData) {
      graphData[key].ratio = (graphData[key].female+graphData[key].ATQ)/graphData[key].male;
    }
  
}

function mergeData(e,i,arr) {
  // pull all relevant data fields into worldJSON for display
  for (var key in graphData[e.properties.name]) {
    e.properties[key] = graphData[e.properties.name][key];
  }
}

function pieChart(displayName,dataObj,selector) {
  // config variables
  var pieWidth = 100;
  var outerRadius = pieWidth / 2;
  var innerRadius = 0;
  var color = d3.scale.category10();
  
  // split dataObj into two corresponding arrays
  var dataSet = [];
  var dataKeys = [];
  for (var key in dataObj) {
    dataSet.push(dataObj[key]);
    dataKeys.push(key);
  }
  
  // drawing the chart
  var pie = d3.layout.pie();
  var arc = d3.svg.arc()
                  .innerRadius(innerRadius)
                  .outerRadius(outerRadius);
  var svg = d3.select('#tooltip-graph')
              .append('svg')
              .attr({
                width: pieWidth,
                height: pieWidth
              });
  var arcs = svg.selectAll('g.arc')
                .data(pie(dataSet))
                .enter()
                .append('g')
                .attr('class','arc')
                .attr('transform','translate(' + outerRadius + ', ' + outerRadius + ')');
  arcs.append('path')
      .attr('fill', function(d,i) {
        return pieColor[i];
      })
      .attr('d',arc);
}

function renderMap(json) {
  var totalRespondents = 0;
  // Rendering and display
  var projection = d3.geo.miller()
                         .scale(width/6)
                         .center([0,30])
  ;
  var path = d3.geo.path()
                   .projection(projection);
  
  var color = d3.scale.quantize()
                      .range([colorFemale, colorATQ, colorMale]);
  
  var zoom = d3.behavior.zoom()
               //.translate([0, 0])
               .scale(1)
               //.xExtent([0,600])
               //.yExtent([0,400])
               .scaleExtent([1,12])
               .on('zoom', zoomed);
  function zoomed() {
    svg.attr('transform','translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')');
  }
 
  var svg = d3.select('.graph')
					  	.append('svg')
					  	.attr('width', width)
					  	.attr('height', height)
              .style('background',colorWater)
              .append('g')
              .call(zoom)
              .append('g');
  
  svg.append('rect')
     .attr({
        class: 'overlay',
        width: width,
        height: height
     });
  
        svg.selectAll('path')
           .data(json.features)
           .enter()
           .append('path')
           .attr('d', path)
           .attr('id', function(d) {
             return d.id;
           })
           .style('fill', function(d){
              totalRespondents = d.properties.ATQ + d.properties.female + d.properties.male + d.properties.NR;
          /* Fill by total respondents */
          //console.log(totalRespondents);
              if (totalRespondents < 20) {
                  return colorLand[1];
              } else if (totalRespondents < 100) {
                 return colorLand[2];
              } else if (totalRespondents < 500) {
                 return colorLand[3];
              } else if (totalRespondents >= 500) {
                 return colorLand[4];
              } else {
                  return colorLand[0];
              }
          /* Fill by gender ratio
              if (typeof d.properties.ratio === "undefined") {
                  return colorLand[0];
              } else if (d.properties.ratio < 0.2) {
                  return colorLand[1];
              } else if (d.properties.ratio < 0.4) {
                 return colorLand[2];
              } else if (d.properties.ratio < 0.6) {
                 return colorLand[3];
              } else if (d.properties.ratio < 0.8) {
                 return colorLand[4];
              } else {
                return colorLand[5];
              }
          */
        })
        .on('mouseover',function(d) {
          var graph = d3.select('.graph').node();
          var mousePos = d3.mouse(graph);
          mousePos[0] = (window.innerWidth-width)/2 + mousePos[0]
          mousePos[0] = mousePos[0] < (window.innerWidth/2) ? mousePos[0] : mousePos[0] - 450;
          //console.log(window.innerWidth);
          var displayName = d.properties.displayName ? d.properties.displayName : d.properties.name.replace(/([A-Z])/g, ' $1').trim();
          if (typeof d.properties.ratio === "undefined") { 
            // then custom message for no data 
            var tooltipData = 'No respondents from '+displayName;
            var totalRespondents = 0;
          } else {
            // create data object for pieChart function
            var pieDataObj = {
              'agender, trans or gender queer respondents': d.properties.ATQ,
              'female respondents': d.properties.female,
              'male respondents': d.properties.male,
              'respondents did not select any of the options provided': d.properties.NR
            };
            pieChart(displayName,pieDataObj,'#tooltip-data');
            var totalRespondents = d.properties.ATQ + d.properties.female + d.properties.male + d.properties.NR;
            var male = Math.round(d.properties.male / totalRespondents * 100) + "%";
            var female = Math.round(d.properties.female / totalRespondents * 100) + "%";
            var other = Math.round((d.properties.NR+d.properties.ATQ) / totalRespondents * 100) + "%";
            var tooltipData = '<ul><li class="legend-color male"><span>' + male + ' male</span></li><li class="legend-color female"><span>' + female + ' female</span></li><li class="legend-color NR"><span>' + other + ' others</span></li><span>-------------<br></span><span>' + totalRespondents + ' total</span></ul>';
          }
          
          d3.select('#tooltip-title')
              .text(displayName + ' (' + totalRespondents + ')');
          d3.select('#tooltip-data')
            .html(tooltipData);
          d3.select('#tooltip').style('left', mousePos[0]+'px')
            .style('top', mousePos[1]+'px');
          // show tooltip
          d3.select('#tooltip').classed('hidden', false);
        })
        .on('mouseout', function() {
          //Hide the tooltip
          d3.select('#tooltip').classed('hidden', true);
          d3.select('#tooltip-graph').select('svg').remove();
        })
        ;
}

d3.csv(surveyData, function(data) {
  loadData(data); // pulls survey data, counts gender and calculates gender ratio per country.
  d3.json(worldJSON,function(json) {
    // pulls loaded data into worldJSON
    json.features.forEach(mergeData);
    renderMap(json);
  });
});
              
            
!
999px

Console