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 id="content" margin-left="auto" margin-right="auto">
  <h1 align="center">
    Which of the following motivated you to adopt a Veg*n diet? </h1>
  <h2 align="center">Based on responses from Faunalytics' <a href="https://faunalytics.org/a-summary-of-faunalytics-study-of-current-and-former-vegetarians-and-vegans/">Study of Current and Former Vegetarians and Vegans</a>.</h2>
  <svg id="canvas" height="500" width="960"></svg>

</div>

            
          
!
            
              body {
  margin: 2em;
}

.axis {
  font-size:14px;
  text-color: #FFFFFF;
  font-weight: bold;
  text-align: justify;
  text-transform: uppercase;}

  .tooltip {
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  position: absolute;
  width: auto;
  height: auto;
  background: none repeat scroll 0 0 white;
  border: 0 none;
  border-radius: 8px 8px 8px 8px;
  box-shadow: -3px 3px 15px #888888;
  color: black;
  font: 12px sans-serif;
  padding: 5px;
  text-align: center;
}

  
            
          
!
            
              //Define Height, Width, and Margins
//This is useful for when we start adding padding when we draw the g element
//Right margin made wider to account for the Bar Chart's legend

var margin = { top: 20, right: 20, left: 20, bottom: 40 };
var width = 960 - margin.left - margin.right;
var height = 648 - margin.top - margin.bottom;

//Define Canvas SVG
var svg = d3
  .select("#canvas")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr(
    "transform",
    "translate(" + margin.left + "," + margin.top + "," + margin.right + ")"
  );

var x = d3
  .scaleBand()
  .rangeRound([0, width])
  .paddingInner(0.2)
  .align(0.2);

var y = d3.scaleLinear().rangeRound([height, 0]);

var colors = d3
  .scaleOrdinal()
  .range(["#F4E8C1", "#A0C1B9", "#70A0AF", "#706993"]);

//Define/populate data array
var data = [
  {
    issue: "protection",
    vegetarian: "69.9",
    vegan: "62.3",
    formerVeg: "26.9",
    formerVegan: "27.1"
  },
  {
    issue: "environment",
    vegetarian: "58.4",
    vegan: "60.4",
    formerVeg: "22.9",
    formerVegan: "23.3"
  },
  {
    issue: "cost",
    vegetarian: "17.5",
    vegan: "32.1",
    formerVeg: "16.9",
    formerVegan: "10.9"
  },
  {
    issue: "health",
    vegetarian: "66.3",
    vegan: "79.2",
    formerVeg: "56.9",
    formerVegan: "63.6"
  },
  {
    issue: "religion",
    vegetarian: "19.3",
    vegan: "32.1",
    formerVeg: "9.2",
    formerVegan: "14.0"
  },
  {
    issue: "social",
    vegetarian: "27.1",
    vegan: "35.8",
    formerVeg: "11.1",
    formerVegan: "14.7"
  },
  {
    issue: "trend",
    vegetarian: "3.6",
    vegan: "17.0",
    formerVeg: "7.4",
    formerVegan: "10.1"
  },
  {
    issue: "disgust",
    vegetarian: "60.8",
    vegan: "67.9",
    formerVeg: "26.1",
    formerVegan: "30.2"
  }
];

console.log("Data:", data);
var keys = ["vegetarian", "vegan", "formerVeg", "formerVegan"];
var issues = [
  "protection",
  "environment",
  "cost",
  "health",
  "religion",
  "social",
  "trend",
  "disgust"
];

//x domain is all issues
x.domain(issues);
//y domain is 0-100 because data represents percentages
y.domain([0, 300]);

//Match colors to group keys
colors.domain(keys);

//Stack data by group
var stacks = d3.stack().keys(keys);

//Creates and array of values to generate the "height" of each group's stack per issue
var dataStacked = stacks(data);
console.log(dataStacked);

//Draw objects
svg
  .selectAll("g")
  .data(dataStacked)
  .enter()
  .append("g")
  .attr("class", "group")
  .attr("fill", function(d) {
    return colors(d.key);
  })
  .selectAll("rect")
  //Data is each "bars" line of data in the dataStacked array
  .data(function(d) {
    return d;
  })
  .enter()
  .append("rect")
  .attr("x", function(d) {
    return x(d.data.issue);
  })
  .attr("y", function(d) {
    return y(d[1]);
  })
  .attr("height", function(d) {
    return y(d[0]) - y(d[1]);
  })
  .attr("width", x.bandwidth())
  .on("mouseover", function() {
    tooltip.style("display", null);
  })
  .on("mouseout", function() {
    tooltip.style("display", "none");
  })
  .on("mousemove", function(d) {
    console.log(d);
    var xPosition = d3.mouse(this)[0] - 5;
    var yPosition = d3.mouse(this)[1] - 5;
    tooltip.attr("transform", "translate(" + xPosition + "," + yPosition + ")");
    tooltip.select("text").text(d);
  });

svg
  .append("g")
  .attr("class", "axis")
  .attr("transform", "translate (0," + height + ")")
  .call(d3.axisBottom(x));

// Create the legend g's
// Note the data join
// Note the transform translate based on the selection element index
var legend = svg
  .append("g")
  .attr("font-family", "sans-serif")
  .attr("font-size", 10)
  .attr("text-anchor", "end")
  .selectAll("g")
  .data(keys.slice().reverse())
  .enter()
  .append("g")
  .attr("transform", function(d, i) {
    return "translate(0," + i * 20 + ")";
  });

// Create rectangles for each legend g
// Pass rect index to Z color ordinal scale
legend
  .append("rect")
  .attr("x", width - 19)
  .attr("width", 19)
  .attr("height", 19)
  .attr("fill", colors);

// Create text for each legend g
// Use the data that it inherits to create the SVG text
legend
  .append("text")
  .attr("x", width - 24)
  .attr("y", 9.5)
  .attr("dy", "0.32em")
  .text(function(d) {
    return d;
  });

//Tooltips
var tooltip = svg
  .append("g")
  .attr("class", "tooltip")
  .style("display", "none");

tooltip
  .append("rect")
  .attr("width", 60)
  .attr("height", 20)
  .attr("fill", "red")
 .attr("transform", "translate(40,0)")
  .style("opacity", 0.5);

tooltip
  .append("text")
  .attr("x", 130)
  .attr("dy", "1.2em")
  .style("text-anchor", "middle")
  .attr("font-size", "12px")
  .attr("font-weight", "bold");

            
          
!
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