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="container">
  <div class="tab-set">
    <div class="tab all" id="active-tab">Location</div>
    <div class="tab gender">Gender</div>
    <div class="tab ethnicity">Ethnicity</div>
    <div class="tab age">Age</div>
  </div>
  <div id="Map">
  </div>
  <div id="tooltip" class="hidden">
    <h3 id="tooltip-title"></h3>
    <div class="inner-cont">
      <div>
        <div class="tooltip-graph" id="gender-graph"></div>
        <p class="tooltip-data" id="gender-data"></p>
      </div>
    </div>
  </div>
</div>
              
            
!

CSS

              
                $colorFemale: #FF1493
$colorATQ: #FFFF00
$colorMale: #000080
$colorNoData: #fff
$colorDarkGrey: #333
$colorLightGrey: #ccc
$colorEM: #EE7600

body
  display: flex
  justify-content: center
  font-family: 'arial', sans-serif
  
.container
  margin: 0 10%

.tab-set
  display: flex
  justify-content: space-around
  flex-wrap: no-wrap
  
.tab
  padding: 10px
  width: 100%
  text-align: center
  border-radius: 5px 5px 0 0
  font-weight: 700
  cursor: pointer
  transition: background-color 0.3s
  &:hover
    background-color: $colorLightGrey
  &#active-tab
    background-color: $colorDarkGrey
    border-color: $colorDarkGrey
    color: white
  
.overlay
  fill: none
  pointer-events: all

#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
    flex-direction: column
    div
      display: flex
      flex-direction: row
      &:nth-last-child(n+2)
        margin-bottom: 1em

  .tooltip-graph
    margin-right: 10px
    &#em-graph
      width: 100px
      height: 2.1em
      background-color: $colorLightGrey
      //box-shadow: inset 1px 1px 1px $colorLightGrey
      border-radius: 3px
      div
        top: 0.25em
        height: 1.7em
        margin: 0.2em
        //box-shadow: 1px 1px 1px $colorLightGrey
        border-radius: 2px
        background-color: $colorEM
        p
          position: relative
          top: -0.6em

  .tooltip-data
    width: 12em
    p, ul
      margin: -1em 0!important
    ul
      list-style: square
      background-color: rgba(0,0,0,0.8)
      padding: 10px 10px 0.2em 30px
      border-radius: 3px
      span
        color: white
      li
        margin-bottom: 0.3em
        &:nth-last-child(1)
          list-style: none
          border-top: 1px solid white
          padding-top: 0.3em
        &.ATQ
          color: $colorATQ
        &.female
          color: $colorFemale
        &.male
          color: $colorMale
        &.NR
          color: $colorNoData
        &.em
          color: $colorEM
    &#em-data
      ul
        padding-top: 0.2em
        padding-bottom: 0.2em
      li
        &:nth-last-child(1)
        list-style: square
        border: none
        padding: none

#map-legend
  margin-top: -20px
  background: $colorDarkGrey
  font-weight: 500
  max-width: 100%
  .legend-colors
    flex-wrap: wrap
    div
      min-width: 4.5em
  .legend-colors, .legend-total
    display: flex
    justify-content: center
    margin: 10px
    div
      display: flex
      justify-content: center
      align-items: center
      padding: 0.4em 0.6em
      height: 1em
      font-weight: 700
      color: black //$colorDarkGrey
      &:nth-child(4)
        color: #fff
      &:nth-child(5)
        color: #fff
      &:nth-child(n+6)
        color: $colorLightGrey
  .legend-total
    div
      &:nth-child(1)
        margin-left: 10px
      &:nth-last-child(1)
        margin-right: 10px
  p
    padding: 20px 20px 0 20px
  h3
    margin: 20px 20px 10px 20px

  p,h3
    display: block
    align-self: flex-start
    color: white

  ul
    display: flex
    flex-direction: row-reverse
    flex-wrap: wrap
    list-style: square
    margin: 10px 20px 10px
    padding-bottom: 40px
    
    span
      color: white
    li
      flex: 0 0 auto
      margin-left: 2.2em
      &.ATQ
        color: $colorATQ
      &.female
        color: $colorFemale
      &.male
        color: $colorMale
      &.NR
        color: $colorNoData
      &.em
        color: $colorEM
      &:nth-last-child(1)
        color: $colorDarkGrey
@media (max-width: 1000px)
  #map-legend
    ul
      flex-direction: column-reverse
      li
        margin-left: 0
        &:nth-last-child(1)
          -webkit-order: -1
          order: -1
          margin-top: 0.3em
          padding-top: 0.3em
          span
            padding-top: 0.3em
            border-top: 1px solid white
@media (max-width: 510px)
  #map-legend
    .legend-colors
      div
        font-size: 0.9em
        padding: 0.3em 0.1em
              
            
!

JS

              
                /* CONFIGURABLE VARIABLES */

var surveyData = 'https://raw.githubusercontent.com/FreeCodeCamp/2016-new-coder-survey/master/clean-data/2016-FCC-New-Coders-Survey-Data.csv';
var worldJSON = 'https://raw.githubusercontent.com/krisgesling/d3-play/master/world-geo2-min.json';

//var surveyData = '2016-FCC-New-Coders-Survey-Data.csv';
//var worldJSON = 'world-geo2-min.json';
var width = 900;
var height = width/7*4;
var maps = ['all','gender','ethnicity','age'];
// Title of fields in dataset
var countryField = "CountryCitizen";
var genderField = "Gender";
var ethnicityField = "IsEthnicMinority";
var ageField = "Age";
// defines the [type, breakpoints between colors for map fill, and description for legend]
var mapFill = {
  all: ['num', [20, 100, 500, 1000],'Number of survey respondents per country.', ['Africa', 'Asia', 'Europe', 'North America', 'South America', 'Oceania']],
  gender: ['percent', [0.15,0.25,0.35,0.45],'Proportion of female, trans*, agender and genderqueer respondents.', ['male', 'female', 'ATQ', 'NR']],
  ethnicity: ['percent', [0.20,0.3,0.4,0.6], 'Proportion of respondents who are members of an ethnic minority in their country.',['Ethnic majority', 'Ethnic minority']],
  age: ['num', [21, 25, 29, 33], 'Average age of respondents per country.', [21, 25, 29, 33]]
    }; 
// Color assignment - remember to also change sass variables
var colors = {
  all: {
    spectrum: ['#c9df8a','#77ab59','#36802d','#234d20', '#112610'],
    Africa: '#500A76',
    Asia: '#7F4200',
    Europe: '#640500',
    'North America': '#E67800',
    'South America': '#1D002C',
    Oceania: '#36802d'
  },
  gender: {
    spectrum: ['#9777A8','#6B2A8F','#500A76','#3A0358','#1D002C'],
    female: '#FF1493',
    ATQ: '#FFFF00',
    male: '#000050',
    NR: '#fff'
  },
  ethnicity: {
    spectrum: ['#DE6862', '#FE0D00', '#B40900', '#640500', '#220200'],
    'Ethnic minority': '#220200',
    'Ethnic majority': '#DE6862'
  },
  age: {
    spectrum: ['#FFB86B','#FF9420','#E67800','#7F4200', '#170C00']
  },
  female: '#FF1493',
  ATQ: '#FFFF00',
  male: '#000050',
  water: '#add8e6',
  NR: '#fff',
  path: ['#333','0.2px'],
};
colors['pie'] = [colors['ATQ'], colors['female'], colors['male'], colors['NR']];

/* OTHER VARIABLE ASSIGNMENT */
var activeGraph = 'all';
var graphData = {};
var liArr = ['NR','ATQ','female','male'];
var liArrDesc = ['No response', 'Trans*, Genderqueer or Agender', 'Female', 'Male'];
var globalStats = {}
function initGlobalStats() {
  for (var i = 0; i < maps.length; i++) {
    for (var j = 0; j < this[3].length; j++) {
      globalStats[this[3][j]] = 0;
    }
  }
}
//mapFill.forEach(initGlobalStats);
/*var globalStats = {
  gender: {
    ATQ: 0,
    female: 0,
    male: 0,
    ethnicity: 0,
    NR: 0
  }
};*/

/* FUNCTIONS */
function loadData(data) {
  // Pulls in statistics and counts them per country, as well as globally.
    // Country constructor
    function Country(displayName) {
      this.total = 0;
      this.female = 0;
      this.ATQ = 0;
      this.male = 0;
      this.NR = 0;
      this.displayName = displayName;
      this.ethnicity = 0;
      this.age = [0,0,0,0,0];
      this.totalAges = 0;
      this.avgAge = 0;
    }
    var continent = {
      Africa: 0,
      Asia: 0,
      Europe: 0,
      'North America': 0,
      'South America': 0,
      Oceania: 0,
      Antarctica: 0
    }

    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(countryNameDisplay);
      }
      graphData[countryName].total++;
      // Increment relevant gender 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].ATQ ++;
          break;
        default:
          graphData[countryName].NR ++;
      }

      // Count ethnic minority status
      if (data[i][ethnicityField] == 1) {
        graphData[countryName].ethnicity ++;
      }
      
      // Tally age groupings based on breakpoints defined in mapFill
      for (var j = 0; j < mapFill['age'][1].length-1; j++) {
        if (data[i][ageField] <= mapFill['age'][1][j]) {
          graphData[countryName].age[j]++;
        }
      }
      if (data[i][ageField] > mapFill['age'][1][4]) {
          graphData[countryName].age[4]++;
      }
      // Calculate average age of each country
      if (data[i][ageField] !== 'NA' && parseInt(data[i][ageField]) > 5 && parseInt(data[i][ageField]) < 100) {
        graphData[countryName].avgAge = graphData[countryName].totalAges < 1 ? parseInt(data[i][ageField]) : (graphData[countryName].avgAge * graphData[countryName].totalAges + parseInt(data[i][ageField])) / (graphData[countryName].totalAges+1);
        graphData[countryName].totalAges ++;
      }
    }
    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;
      // Tally each countries stats for globalStats
      for (var j in graphData[key]) {
        if (globalStats[j] !== 'undefined') {
          globalStats[j] += graphData[key][j];
        }
      }
    }
}
// END FUNCTION loadData

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];
  }
}
// END FUNCTION mergData

function pieChart(dataSet,selector) {
  // General use function to create a pie chart
  // config variables
  var pieWidth = 100;
  var outerRadius = pieWidth / 2;
  var innerRadius = 0;
  var color = d3.scale.category10();

  // drawing the chart
  var pie = d3.layout.pie();
  var arc = d3.svg.arc()
                  .innerRadius(innerRadius)
                  .outerRadius(outerRadius);
  var svg = d3.select(selector)
              .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 colors.pie[i];
      })
      .attr('d',arc);
} // END pieChart function

function percentify(num,total) {
  // Just returns a number as a percentage oftype string
  var percent = Math.round( num / total * 100);
  if (percent < 10) {
    percent = Math.round( num / total * 1000) / 10;
  }
  return percent + '%';
}
// END FUNCTION percentify

function sizeChange() {
  var graphWidth = document.getElementById('gender-map').offsetWidth;
  d3.select('g').attr('transform', 'scale(' + graphWidth/900 + ")");
  d3.select('svg')
    .attr('height', graphWidth/7*4);
}
// END FUNCTION sizeChange

function fillToLegendConv(num) { 
  switch (activeGraph) {
    case 'all':
      return num;
      break;
    case 'gender':
      return num * 100 + '%';
      break;
    default:
      return num;
  }
}

function renderMap() {
  d3.json(worldJSON,function(json) {
    // pulls loaded data into worldJSON
    json.features.forEach(mergeData);
    function zoomed() {
      svg.attr('transform','translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')');
    }
    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([colors.gender.female, colors.gender.ATQ, colors.gender.male]);

    var zoom = d3.behavior.zoom()
                 .scale(1)
                 .scaleExtent([1,12])
                 .on('zoom', zoomed);

    var svg = d3.select('#gender-map')
                .append('svg')
                .attr('width', '100%')
                .attr('height', height)
                .attr('id','gender-map-svg')
                .style('background', colors.water)
                .append('g')
                .call(zoom)
                .append('g');
    var legend = d3.select('#gender-map')
                   .append('div')
                   .attr('width', width + 'px')
                   .attr('id', 'map-legend')
                   .html('<p class="description">' + mapFill[activeGraph][2] + '</p>')

    // Create map legend colors and labels
    var legendColors = legend.append('div')
                   .attr('class','legend-colors');
    if (mapFill[activeGraph][0] === 'percent') {
      var legendText = ['0-' + mapFill[activeGraph][1][0] *100 + '%', mapFill[activeGraph][1][0] *100 +1 + '-' + mapFill[activeGraph][1][1] *100 + '%', mapFill[activeGraph][1][1] *100 +1 + '-' + mapFill[activeGraph][1][2] *100 + '%', mapFill[activeGraph][1][2] *100 +1 + '-' + mapFill[activeGraph][1][3] *100 + '%', mapFill[activeGraph][1][3] *100 +1 + '-100%'];
    } else if (mapFill[activeGraph][0] === 'num') {
      var legendText = ['0-' + mapFill[activeGraph][1][0], mapFill[activeGraph][1][0]+1 + '-' + mapFill[activeGraph][1][1], mapFill[activeGraph][1][1]+1 + '-' + mapFill[activeGraph][1][2], mapFill[activeGraph][1][2]+1 + '-' + mapFill[activeGraph][1][3], mapFill[activeGraph][1][3]+1 + '+'];
    }

    for (var i = 0; i < colors[activeGraph].spectrum.length; i++) {
      legendColors.append('div')
            .style('background', colors[activeGraph].spectrum[i])
            .text(legendText[i]);
    }

    var globalTotal = globalStats.ATQ + globalStats.female + globalStats.male + globalStats.NR;
    legend.append('h3')
          .text('Global statistics');
    var legendTotal = legend.append('div')
          .attr('class','legend-total');

    for (var k = 0; k < mapFill[activeGraph][3].length; k++) {
      legendTotal.append('div')
          .style('background', colors[activeGraph][mapFill[activeGraph][3][k]])
          .style('width', percentify(globalStats[mapFill[activeGraph][3][k]], globalTotal));
    }

    var globalLegend = legend.append('ul');
    //var globalStatsWidth 
    for (var i = 0; i < liArr.length; i++) {
      globalLegend.append('li')
                  .attr('class', 'legend-color ' + mapFill[activeGraph][3])
                  .html('<span>' + percentify(globalStats[liArr[i]],globalTotal) + ' ' + liArrDesc[i] + '</span>');
    }
    globalLegend.append('li')
                .attr('class', 'legend-color total')
                .html('<span>' + globalTotal + ' Total</span>');

    svg.append('rect')
       .attr({
          class: 'overlay',
          width: width,
          height: height
       });

          svg.selectAll('path')
             .data(json.features)
             .enter()
             .append('path')
             .attr('d', path)
             .attr('stroke', colors['path'][0])
             .attr('stroke-width', colors['path'][1])
             .attr('id', function(d) {
               return d.id;
             })
              // Define country fill rules
             .style('fill', function(d){
                totalRespondents = d.properties.ATQ + d.properties.female + d.properties.male + d.properties.NR;

                switch (activeGraph) {
                  case 'all':
                    var fillTest = totalRespondents;
                    break;
                  case 'gender':
                    var fillTest = (d.properties.female + d.properties.ATQ)/totalRespondents;
                    break;
                  case 'ethnicity':
                    var fillTest = d.properties.ethnicity / totalRespondents;
                    break;
                  case 'age':
                    var fillTest = parseInt(d.properties.avgAge);
                    break;
                }

                if (fillTest <= mapFill[activeGraph][1][0]) {
                     return colors[activeGraph].spectrum[0];
                  } else if (fillTest <= mapFill[activeGraph][1][1]) {
                     return colors[activeGraph].spectrum[1];
                  } else if (fillTest <= mapFill[activeGraph][1][2]) {
                     return colors[activeGraph].spectrum[2];
                  } else if (fillTest <= mapFill[activeGraph][1][3]) {
                     return colors[activeGraph].spectrum[3];
                  } else if (fillTest > mapFill[activeGraph][1][3]) {
                     return colors[activeGraph].spectrum[4];
                  } else {
                      return colors['NR'];
                  }
          })
          // Everything for tooltips
          .on('mouseover',function(d) {
            var graph = d3.select('#gender-map').node();
            var mousePos = d3.mouse(graph);
            mousePos[0] = (window.innerWidth-width)/2 + mousePos[0]
            mousePos[0] = mousePos[0] < (window.innerWidth/1.5) ? mousePos[0] : mousePos[0] - 340;

            var displayName = d.properties.displayName ? d.properties.displayName : d.properties.name.replace(/([A-Z])/g, ' $1').trim();
            totalRespondents = d.properties.ATQ + d.properties.female + d.properties.male + d.properties.NR;
            totalRespondents = totalRespondents ? totalRespondents : 0;
            
            if (typeof(d.properties.ratio) === "undefined" || (activeGraph === 'age' && d.properties.totalAges == 0)) {
              // then custom message for no data
              var tooltipData = 'No respondents from '+displayName;
              d3.select('#em-graph')
                .style('display','none');
            } else {
              // create pie chart and legend
              pieChart([d.properties.ATQ, d.properties.female, d.properties.male, d.properties.NR],'#gender-graph');
              var femaleText = '<li class="legend-color female"><span>' + percentify(d.properties.female,totalRespondents) + ' Female</span></li>';
              var maleText = '<li class="legend-color male"><span>' + percentify(d.properties.male,totalRespondents) + ' Male</span></li>';
              var atqText = '<li class="legend-color ATQ"><span>' + percentify(d.properties.ATQ,totalRespondents) + ' Genderqueer, <br>Trans* or Agender</span></li>';
              var noResponseText = d.properties.NR ? '<li class="legend-color NR"><span>' + percentify(d.properties.NR,totalRespondents) + ' no response</span></li>' : '';
              if (d.properties.male > d.properties.female) {
                var orderedText = maleText + femaleText + atqText;
              } else {
                var orderedText = femaleText + maleText + atqText;
              }
              var tooltipData = '<ul>' + orderedText + noResponseText + '<li class="legend-color"><span>' + totalRespondents + ' Total</span></li></ul>';

            // Create ethnic minority stacked bar graph
            // text positioning
            var percentage = parseInt(d.properties.ethnicity / totalRespondents * 100 );
            var percSide = 'left';
            if (percentage > 50) {
              percentage -= percentage*1.5;
              percSide = 'right';
            }
            d3.select('#em-graph')
              .style('display','block')
              .append('div')
              .style('width', function(){
                if (d.properties.ethnicity / totalRespondents > 0.94) {
                  return '94%';
                }
                return percentify( d.properties.ethnicity, totalRespondents );
              })
              .html('<p>' + percentify( d.properties.ethnicity, totalRespondents) + '</p>')
              .select('p')
              .style(percSide, ( percentage + 5 + 'px' ));
            d3.select('#em-data')
              .html('<ul><li class="legend-color em"><span>Ethnic minority</span></li></ul>');
            }

            d3.select('#tooltip-title')
                .text(displayName + ' (' + totalRespondents + ')');
            d3.select('#gender-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 tooltip
            d3.select('#tooltip').classed('hidden', true);
            d3.select('#gender-graph').select('svg').remove();
            d3.select('#em-graph').select('div').remove();
            d3.select('#em-data').select('ul').remove();
          });
    sizeChange();
  });
}
// END FUNCTION renderMap


/* PRIMARY CALLS */
d3.csv(surveyData, function(data) {
  loadData(data); // pulls survey data, counts gender and calculates gender ratio per country.
  renderMap();
});


d3.select(window)
  .on("resize", sizeChange);

window.onload = function() {
  var tabs = document.getElementsByClassName('tab');
  for (var i = 0; i < tabs.length; i++) {
    var tab = tabs[i];
    tab.onclick = function() {
      document.getElementById('active-tab').removeAttribute('id');
      activeGraph = this.className.replace('tab ','');
      this.setAttribute('id','active-tab');
      d3.select('#gender-map').select('svg').remove();
      d3.select('#gender-map').select('div').remove();
      renderMap();
    }
  }
};
              
            
!
999px

Console