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. You can use the CSS from another Pen by using it's URL and the proper URL extention.

+ 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.

Details

Privacy

Go PRO Window blinds lowered to protect code. Code Editor with window blinds (raised) and a light blub turned on.

Keep it secret; keep it safe.

Private Pens are hidden everywhere on CodePen, except to you. You can still share them and other people can see them, they just can't find them through searching or browsing.

Upgrade to PRO

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.

Template

Make Template?

Templates are Pens that can be used to start other Pens quickly from the create menu. The new Pen will copy all the code and settings from the template and make a new Pen (that is not a fork). You can view all of your templates, or learn more in the documentation.

Template URL

Any Pen can act as a template (even if you don't flip the toggle above) with a special URL you can use yourself or share with others. Here's this Pen's template URL:

Screenshot

Screenshot or Custom Thumbnail

Screenshots of Pens are shown in mobile browsers, RSS feeds, to users who chose images instead of iframes, and in social media sharing.

This Pen is using the default Screenshot, generated by CodePen. Upgrade to PRO to upload your own thumbnail that will be displayed on previews of this pen throughout the site and when sharing to social media.

Upgrade to PRO

HTML

              
                <!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <link rel="stylesheet" href="styling.css" />
    <title>Visualize Data with a Choropleth Map</title>
</head>
<body>
    <main>
        <div class="container">
            <header id="title">
                <h1>United States Educational Attainment</h1>
                <h3 id="description">Percentage of adults age 25 and older with a bachelor's degree or higher (2010-2014)</h3>
              <h2><a href="http://cselko.offyoucode.co.uk/Websites/Free_Code_Camp/Data_Visualisation/Visualize_Data_with_a_Choropleth%20Map/" target="_blank">Link to the workable page</a></h2>
                <div>
                    <input type="color" id="colorInput" />
                </div>
            </header>
            <svg width="960" height="700"></svg>
        </div>
    </main>
    <script src="https://d3js.org/d3.v5.min.js"></script>
    <script src="https://unpkg.com/topojson@3.0.2/dist/topojson.min.js"></script>
    <script src="js/index.js"></script>
</body>
</html>
              
            
!

CSS

              
                main {
    text-align: center;
    background-color: #c6e3ff;
    color: black;;
}

#title {
	position: sticky;
    top: 0;
}

#colorInput{
    opacity: 0;
}

.state {
    fill: #7b7b7b;
    stroke: black;
    stroke-width: 0.5;
}

.county:hover {
    fill: red;
}

#tooltip {	
    position: absolute;	
    padding: 10px;				
    font: 12px sans-serif;		
    background: oldlace;	
    border: 0px;		
    border-radius: 8px;			
    pointer-events: none;
    box-shadow: 4px 4px 4px grey;
}

.selector {
    pointer-events: all;
    stroke: grey;
    stroke-width: 1;
}

.selector:hover {
	stroke: black;
    stroke-width: 2.5;
}

.selected {
    stroke: black;
    stroke-width: 2;
}

.non-selected {
    stroke: none;
    stroke-width: none;
}

              
            
!

JS

              
                "use strict";
const svg = d3.select("svg");

let color = "darkgreen";
svg.append("defs");
d3.select("defs").append("linearGradient")
    .attr("id", "grad")
    .attr("x1", "0%")
    .attr("x2", "100%")
    .attr("y1", "0%")
    .attr("y2", "0%");
const grad = d3.select("linearGradient");
grad.append("stop")
    .attr("offset", "0%")
    .style("stop-color", "white");
grad.append("stop")
    .attr("id", "changeColor")
    .attr("offset", "100%")
    .style("stop-color", color);
    
// create zoom-effect:
const g = svg.append("g");

svg.call(d3.zoom()
    .on("zoom", () => {
    g.attr("transform", d3.event.transform);
}));

// Create a div for tooltip:
const tooltip = d3.select("body")
    .append("div")
    .attr("id", "tooltip")
    .style("opacity", 0);

const callTooltip = function (x, y, content) {
    tooltip.style("left", (d3.event.pageX + x) + "px")
        .style("top", (d3.event.pageY + y) + "px")
        .style("opacity", 0.9)
        .html(content);
}

let range =  null, eventRect = true; // for clickable legend


const pathGenerator = d3.geoPath();

// load these datas to the same scope:
const educationDataFile = "https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/for_user_education.json";
//const educationDataFile = "data/for_user_education.json";
const countiesDataFile = "https://raw.githubusercontent.com/no-stack-dub-sack/testable-projects-fcc/master/src/data/choropleth_map/counties.json";
//const countiesDataFile = "data/counties.json";

Promise.all([
    d3.json(countiesDataFile),
    d3.json(educationDataFile)
]).then(([countiesData, educationData]) => {
    // collect dataset
    const countyWithEducation = {};
    educationData.forEach(d => {
        countyWithEducation[d.fips] = {
            county: d.area_name,
            bachelorsOrHigher: d.bachelorsOrHigher,
            state: d.state
        };
    });
    render(countiesData, educationData, countyWithEducation);
});

const render = (countiesData, educationData, countyWithEducation) => {
    d3.select("#colorInput")
        .attr("opacity", 0)
        .style("opacity", 0);
    // create color scale:
    let bachelors = d => d.bachelorsOrHigher;
    const min = d3.min(educationData, bachelors);
    const max = d3.max(educationData, bachelors);
    const colorScale = d3.scaleLinear()
        .domain([min, max])
        .range(["white", color]);
    const createGeoJSON = (geometryCollection) => topojson.feature(countiesData, countiesData.objects[geometryCollection]);
    
    g.selectAll(".state")
        .data(createGeoJSON("states").features)
        .enter()
        .append("path")
            .attr("class", "state")
            .attr("d", pathGenerator);
    
    bachelors = (d) => countyWithEducation[d.id].bachelorsOrHigher; 
    const countyGroup = g.selectAll(".county")
        .data(createGeoJSON("counties").features);
    const countyGroupEnter = countyGroup.enter()
        .append("path")
            .attr("class", "county")
            .attr("d", pathGenerator)
            .attr("data-fips", d => d.id)
            .attr("data-education", d => bachelors(d));
    
    // update cycle:
    const changeStroke = (element, width) => {
        element.attr("stroke", "black")
            .attr("stroke-width", width);
    };
    countyGroupEnter.merge(countyGroup)
        .transition().duration(1)
        .delay((d, i) => i + 1)
            .attr("fill", d => colorScale(bachelors(d)))
            .attr("opacity", function(d) {
                const element = d3.select(this);
                if (range !== null) {
                    if (bachelors(d) > range 
                    && bachelors(d) < (range +10)) {
                        changeStroke(element, 1);
                        return 1;
                    } else {
                        changeStroke(element, 0);
                        return 0.1;
                    }
                } else {return 1;}
            })
    ;
    countyGroupEnter.on("mouseover", function(d) {
            const content = `
                <h4>${countyWithEducation[d.id].county} ${countyWithEducation[d.id].state}</h4>
                <p>${bachelors(d)}%</p>
            `;
            callTooltip(10, 10, content);
            tooltip.attr("data-education", bachelors(d));
        })
        .on("mouseout", () => tooltip.style("opacity", 0));
    countyGroup.exit().remove();
    // create color-legend:
    
    const legendHeight = 20;
    const legendWidth = 500;
    const xScale = d3.scaleLinear()
        .domain([min / 100, max / 100])
        .range([0, legendWidth])
        .nice();
    const colorLegend = g.append("g").attr("class", "colorLegend");
    
    // change color on color legend:
    d3.select("#changeColor")
        .style("stop-color", color);
    
    colorLegend.append("rect")
        .attr("y", - legendHeight)
        .attr("width", legendWidth)
        .attr("height", legendHeight)  
        .attr("stroke", "none")
        .attr("fill", "url(#grad)");
    
    d3.selectAll(".selector").remove();
    for (let i = 0; i < 8; i++) {
        colorLegend.append("rect")
            .attr("data-precent", i * 10)
            .attr("class", "selector")
            .attr("y", - legendHeight)
            .attr("x", 0 + i * legendWidth / 8)
            .attr("width", legendWidth / 8)
            .attr("height", legendHeight)  
            .attr("stroke", "black")
            .attr("fill", "none");
    }
    
    const eventPrecent = (event) => + d3.event.target.dataset.precent;
    colorLegend.selectAll(".selector")
        .on("mouseover", () => {
            let content;
            const precent = eventPrecent(event);
            if (precent === range) {
                content = `<p>Return to the full range...<p>`;
            } else {   
                content = `
                    <p>Click to choose ${precent} - ${precent +10}% range...</p><p>Double Click to choose color...</p>
                `;
            }
            callTooltip(10, 10, content);
            
        }).on("click", () => {
            // change description:
            const description = (range) => {
                d3.select("#description")
                    .text(`Percentage of adults age 25 and older with a bachelor's degree or higher (${range})`);
            };
            if (range === eventPrecent(event)) {
                //  switch off the selection effect
                d3.selectAll(".selector")
                    .classed("selected", false)
                    .classed("non-selected", true)
                ;
                range = null;
                description(`2010-2014`);
                render(countiesData, educationData, countyWithEducation);
            } else {
                //  switch on the selection effect
                d3.selectAll(".selector")
                    .classed("selected", false)
                    .classed("non-selected", true)
                ;
                d3.select(d3.event.toElement)
                    .classed("selected", true)
                    .classed("non-selected", false)
                ;
                range = eventPrecent(event);
                description(`${range}-${range + 10}%`);
                render(countiesData, educationData, countyWithEducation);
            }
        }
        ).on("mouseout", () => {
            
        }).on("dblclick", () => {
            event.preventDefault();
            d3.select("#colorInput")
                .attr("value", color)
                .style("opacity", 1)
                .attr("opacity", null)
            ;
        });
        
    const xAxis = d3.axisBottom(xScale)
        .tickFormat(d3.format(".0%"))
        .tickSize(- legendHeight)
        .tickPadding(5);
    colorLegend.call(xAxis)
            .attr("transform", `translate(${350}, ${40})`);
    
    d3.select("#colorInput")
        .on("change", function() {
            color = this.value;
            render(countiesData, educationData, countyWithEducation);
        });
//    console.log(countyWithEducation);
}

              
            
!
999px
The Pen is mightier than the sword.

Console