css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

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.

            
              <div class="container">
    <div id="heading">
      <h1 id="title">Monthly Global Land-Surface Temperature</h1>
      <h2 id="subtitle">1753 - 2015 (September)</h2>
      <div id="description">Temperatures are in Celsius and reported as <a href="http://data.giss.nasa.gov/gistemp/FAQ.html#q101">anomalies</a> relative to the Jan 1951-Dec 1980 average temperature of 8.66 &deg;C +/- 0.07</div>
    </div>
    <div id="chart"></div>
  </div>
            
          
!
            
              path.domain{
  fill: none;
}

.tooltip {
  background: steelblue;
  color: white;
  position: absolute;
  padding: 0.5em 0.9em;
  width: 100px;
  border-radius: 5px;
}

.tooltip h1,
.tooltip h2 {
  padding: 0;
  margin: 0.15em;
  text-align: center;
}

.tooltip h1 {
  font-family: 'Oswald', serif;
}

.tooltip h2 {
  font-size: 1.2em;
}

.label {
  font-size: 1.6em;
  font-family: 'Oswald', serif;
}

#heading {
  text-align: center;
  color: #555;
}

#chartTitle,
#chartSubTitle {
  font-family: 'Oswald', serif;
}

.axis .tick,
.legend,
#chartDescription {
  font-family: 'Rokkitt', serif;
}

.container {
  background-color: #eee;
  margin-top: 10vh;
  box-shadow: 0px 23px 14px -14px black;
}

body {
  background-color: #ccc;
}

            
          
!
            
              function heatMap() {
  const margin = { top: 0, right: 180, bottom: 120, left: 100 };
  let width = 1200 - margin.left - margin.right;
  let height = 720 - margin.top - margin.bottom;
  let yearFormat = d => d;
  let monthFormat = d => d;
  let tempFormat = d => d;
  const xScale = d3.scale.ordinal();
  const yScale = d3.scale.ordinal();
  const zScale = d3.scale.quantile();
  const xAxis = d3.svg.axis().orient("bottom");
  const yAxis = d3.svg.axis().orient("left");
  const chartColors = [
    "#5081D6",
    "#53D4E0",
    "#55C990",
    "#61E053",
    "#E1F58E",
    "#BDD64C",
    "#CED63C",
    "#E0C13F",
    "#C99342",
    "#C97200",
    "#E06F3F",
    "#D63839"
  ];
  let legendPadding = 30;
  const xTextBottomPadding = 20;
  const monthDict = {
    1: "January",
    2: "February",
    3: "March",
    4: "April",
    5: "May",
    6: "June",
    7: "July",
    8: "August",
    9: "September",
    10: "October",
    11: "November",
    12: "December"
  };

  let xLabel = "";
  let yLabel = "";

  function chart(selection) {
    d3.select(this).html(""); //Delete any other charts before redrawing

    selection.each(data => {
      const svg = d3
        .select(this)
        .append("svg")
        .classed("main", true)
        .attr({
          width: width + margin.left + margin.right,
          height: height + margin.top + margin.bottom
        })
        .append("g")
        .classed("chartContainer", true)
        .attr({
          transform: `translate(${margin.left},${margin.top})`
        });

      const tooltip = d3
        .select(this)
        .append("div")
        .attr({ id: "tooltip" })
        .style({
          opacity: 0
        });

      const chartData = d3
        .nest()
        .key(d => d.year)
        .key(d => d.month)
        .rollup(d => d[0].variance)
        .entries(data.monthlyVariance);

      const years = chartData.map(d => +d.key);
      const months = chartData[0].values.map(d => +d.key);
      const variances = d3.merge(
        chartData.map(d => d.values.map(x => x.values))
      );

      xScale.domain(years).rangeBands([0, width]);

      yScale.domain(months).rangeBands([height, 0]);

      zScale.domain(variances).range(chartColors);

      xAxis.scale(xScale).tickValues(years.filter((d, i) => i % 20 !== 0));
      yAxis.scale(yScale).tickFormat(day => monthDict[day]);

      const axes = svg
        .selectAll(".axis")
        .data([
          {
            class: "x",
            axis: xAxis,
            x: 0,
            y: height,
            id: "x-axis"
          },
          {
            class: "y",
            axis: yAxis,
            x: 0,
            y: 0,
            id: "y-axis"
          }
        ])
        .enter()
        .append("g")
        .attr({
          class: d => d.class + " axis",
          "text-anchor": "end",
          transform: d => `translate(${d.x},${d.y})`,
          id: d => d.id
        });

      axes.each(d => d3.select(this).call(d.axis));

      const yText = d3
        .select(".y.axis")
        .append("text")
        .classed("label", true)
        .attr({
          y: margin.left / -2,
          x: 0 - height / 2, //Because of rotation
          transform: "rotate(-90)",
          "text-anchor": "middle"
        })
        .text(yLabel);

      const xText = d3
        .select(".x.axis")
        .append("text")
        .classed("label", true)
        .attr({
          x: width / 2,
          y: margin.bottom / 2,
          "text-anchor": "middle"
        })
        .text(xLabel);

      const blockWidth = width / years.length,
        blockHeight = yScale.rangeBand();

      svg
        .append("g")
        .selectAll("rect")
        .data(data.monthlyVariance)
        .enter()
        .append("rect")
        .attr({
          x: d => xScale(d.year),
          y: d => yScale(d.month),
          height: blockHeight,
          width: blockWidth,
          "data-month": d => d.month - 1,
          "data-year": d => d.year,
          "data-temp": d => d.variance,
          class: "cell"
        })
        .style({
          fill: d => zScale(d.variance),
          stroke: "none",
          "stroke-width": 0,
          margin: 0,
          padding: 0
        })
        .on("mouseover", d => {
          tooltip
            .style({
              opacity: 0.8,
              top: d3.event.pageY - 70 + "px",
              left: d3.event.pageX + 60 + "px"
            })
            .attr({ "data-year": d.year })
            .html(
              `<h1>${d.year}</h1> <h2>${monthDict[d.month]}</h2><h2>${
                d.variance
              }&deg;C</h2><h2>${(d.variance + data.baseTemperature).toFixed(
                4
              )}&deg;C</h2>`
            );
        })
        .on("mouseout", () => tooltip.style("opacity", 0));

      const legendX = width + legendPadding,
        legendY = margin.top + height / 3,
        legend = svg
          .append("g")
          .selectAll(".legend")
          .data(zScale.quantiles())
          .enter()
          .append("g")
          .attr({
            transform: (d, i) => `translate(${legendX},${legendY - i * 20})`,
            id: "legend"
          });

      legend
        .append("rect")
        .attr({
          width: 20,
          height: 20
        })
        .style("fill", zScale);

      legend
        .append("text")
        .attr("x", 26)
        .attr("y", 10)
        .attr("dy", ".35em")
        .text(d => `${d.toFixed(4)}ºC`);
    }); //selection
  }

  chart.width = _ => {
    if (!arguments.length) return width;
    width = _;
    return chart;
  };

  chart.height = _ => {
    if (!arguments.length) return height;
    height = _;
    return chart;
  };

  chart.xLabel = _ => {
    if (!arguments.length) return xLabel;
    xLabel = _;
    return chart;
  };

  chart.yLabel = _ => {
    if (!arguments.length) return yLabel;
    yLabel = _;
    return chart;
  };

  chart.yearFormat = _ => {
    if (!arguments.length) return yearFormat;
    yearFormat = _;
    return chart;
  };

  chart.monthFormat = _ => {
    if (!arguments.length) return monthFormat;
    monthFormat = _;
    return chart;
  };

  chart.tempFormat = _ => {
    if (!arguments.length) return tempFormat;
    tempFormat = _;
    return chart;
  };

  chart.legendPadding = _ => {
    if (!arguments.length) return legendPadding;
    legendPadding = _;
    return chart;
  };

  return chart;
}

window.onload = function () {
  d3.json("https://gregoftheweb.com/temps.json", (error, data) => {
    if (error) throw error;
    const tempsChart = heatMap()
      // .yLabel("Month")
      // .xLabel("Year");
    d3
      .select("#chart")
      .datum(data)
      .call(tempsChart); 
  });
};
            
          
!
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.
Loading ..................

Console