Pen Settings

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

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

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

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

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.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              html { height: 100%; }
body {
  align-items: center;
  background-color: #1D1E22;
  display: flex;
  justify-content: center;
  height: 100%;
}

svg {
  background-color: #fff;
  padding: 120px 60px 160px 120px;
}

.title {
  font-size: 24px;
}

div.tooltip {
  background: rgba(112, 127, 140, .85);
  border: none;
  border-radius: 2px;
  color: #fff;
  font-size: 18px;
  padding: 10px 20px;
  pointer-events: none;
  position: absolute;
  text-align: center;
  width: 150px;
}

.cell:hover {
  stroke: #333 !important;
  stroke-width: 2px !important;
}
            
          
!
            
              // store dat in variable
const dataURI = 'https://raw.githubusercontent.com/freeCodeCamp/ProjectReferenceData/master/global-temperature.json'

// set up svg
const w = 1200
const h = 500
const margin = { top: 30, right: 10, bottom: 30, left: 10 }
const cellSize = 50
const svg = d3.select('body')
              .append('svg')
              .attr('width', w)
              .attr('height', h)

// set up chart title
svg.append('text')
   .attr('transform', `translate(${w/2}, ${margin.top - 100})`)
   .attr('class', 'title')
   .attr('id', 'title')
   .style('text-anchor', 'middle')
   .text('Monthly Global Land-Surface Temperature')

// set up chart subtitle
svg.append('text')
   .attr('transform', `translate(${w/2}, ${margin.top - 70})`)
   .attr('class', 'description')
   .attr('id', 'description')
   .style('text-anchor', 'middle')
   .text('1753 - 2015: base temperature 8.66°C')

// read in data
d3.json(dataURI, { crossOrigin: 'anonymous' }).then(({ monthlyVariance }) => {
  
  // set base temp
  const base = 8.66
  
  // separate data into variables
  const variances = monthlyVariance.map(item => item.variance)
  const temps = monthlyVariance.map(item => base + item.variance)
  const years = monthlyVariance.map(item => item.year)
  
  // set up colors
  const colors = ["#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027", "#a50026"]
  
  const colorScale = d3.scaleQuantize()
                       .domain(d3.extent(variances))
                       .range(colors)
  
  // set up x scale
  const xScale = d3.scaleLinear()
                   .domain(d3.extent(years))
                   .range([margin.left, w - margin.right])
  
  // set up y scale
  let months = Array.from(Array(13).keys()) // ES6 technique to create N-element array [0, 1, ..., N-1] - https://goo.gl/i6YT7D
  months.shift()
  months = months.map(month => moment(month, 'MM').format('MMMM'))
  
  const yScale = d3.scaleBand()
                   .domain(months.reverse()) // reverse months for yAxis
                   .range([h, 0])
  
  // append div for use as tooltip
  const tooltip = d3.select('body')
                    .append('div')
                    .attr('class', 'tooltip')
                    .attr('id', 'tooltip')
                    .style('opacity', 0)
  
  // reverse months back to normal
  months.reverse()
  
  // set up heat map cells
  svg.selectAll('rect')
     .data(monthlyVariance)
     .enter()
     .append('rect')
     .attr('x', d => xScale(d.year))
     .attr('y', d => (d.month - 1) * (h / 12))
     .attr('width', w / (d3.max(years) - d3.min(years)))
     .attr('height', h / 12)
     .attr('data-month', d => d.month - 1)
     .attr('data-year', d => d.year)
     .attr('data-temp', d => base + d.variance)
     .attr('class', 'cell')
     .style('fill', d => colorScale(d.variance))
     // set up mouseover to modify tooltip div
     .on('mouseover', (d, i) => {
       tooltip.transition()
              .duration(200)
              .style('opacity', 0.9)
       tooltip.html(`
                ${d.year} - ${months[d.month - 1]}
                <br />
                <br />
                ${(base + d.variance).toFixed(2)}°C
                <br />
                ${d.variance.toFixed(2)}°C
              `)
              .attr('data-year', d.year)
              .style('left', (d3.event.pageX) + 20 + 'px')
              .style('top', (d3.event.pageY) + 'px')
     })
     // set up mouseout to modify tooltip div
     .on('mouseout', d => {
       tooltip.transition()
              .duration(200)
              .style('opacity', 0)
     })
  
  // set up x axis
  const xAxis = d3.axisBottom(xScale)
                  .tickFormat(d3.format('d'))
                  .tickSizeOuter(0)
                  .ticks(20)
  
  // set up y axis
  const yAxis = d3.axisLeft(yScale)
                  .tickSizeOuter(0)
  
  // add axes to chart
  svg.append('g')
     .attr('id', 'x-axis')
     .attr('transform', `translate(0, ${h})`)
     .call(xAxis)  
  svg.append('g')
     .attr('id', 'y-axis')
     .attr('transform', `translate(${margin.left}, 0)`)
     .call(yAxis)
  
  // set up legend
  const legend = svg.append('g')
                    .attr('id', 'legend')
                    .attr('class', 'legend')
                    .attr('transform', `translate(${margin.left}, ${h + 40})`)
  
  // add legend squares
  const sqWidth = 50
  const sqHeight = 50
  
  legend.selectAll('rect')
        .data(colors)
        .enter()
        .append('rect')
        .attr('width', sqWidth)
        .attr('height', sqHeight)
        .attr('x', (d, i) => i * sqWidth)
        .attr('y', 0)
        .style('fill', (d, i) => colors[i])
  
  legend.select('.legend')
        .data()
  
  // set up legend scale
  const legendScale = d3.scaleLinear()
                       .domain(d3.extent(temps))
                       .range([0, colors.length * sqWidth])
  
  let tempTicks = []
  const minTemp = d3.min(temps)
  const maxTemp = d3.max(temps)
  for (let i = 0; i <= 12; i++) {
    if (i === 0) {
      tempTicks.push(minTemp)
    } else if (i > 0 && i < 11) {
      tempTicks.push(tempTicks[i - 1] + ((maxTemp - minTemp) / 11))
    } else if (i === 11) {
      tempTicks.push(maxTemp)
    }
  }
  
  // set up legend axis
  const legendAxis = d3.axisBottom(legendScale)
                       .tickSize(10, 0)
                       .tickFormat(d3.format('.1f'))
                       .tickSizeOuter(0)
                       .tickValues(tempTicks)
  
  legend.append('g')
        .attr('transform', `translate(0, ${sqHeight})`)
        .call(legendAxis)
})
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console