Skip to content

Instantly share code, notes, and snippets.

@sepans
Last active January 8, 2023 19:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sepans/98b1ac007cc0789970e7 to your computer and use it in GitHub Desktop.
Save sepans/98b1ac007cc0789970e7 to your computer and use it in GitHub Desktop.
d3.js and p5.js
// port of http://bl.ocks.org/mbostock/3048450 into p5.js
function setup() {
/*
This section of code is the exact copy of d3.js example
*/
// Generate a Bates distribution of 10 random variables.
var values = d3.range(5000).map(d3.random.bates(10));
// A formatter for counts.
var formatCount = d3.format(",.0f");
var margin = {top: 10, right: 30, bottom: 30, left: 30},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, 1])
.range([0, width]);
// Generate a histogram using twenty uniformly-spaced bins.
var data = d3.layout.histogram()
.bins(x.ticks(20))
(values);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d.y; })])
.range([height, 0]);
/*
up tp here the code is exactly the same as d3.js example.
below p5.js translation starts.
*/
createCanvas(width, height);
/*
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
*/
for(var i = 0; i< data.length; i++) {
var d = data[i];
push();
translate(x(d.x), y(d.y));
/*
bar.append("rect")
.attr("x", 1)
.attr("width", x(data[0].dx) - 1)
.attr("height", function(d) { return height - y(d.y); });
*/
fill(70, 130, 180);
noStroke();
rect(1, 1, x(data[0].dx) - 1, height - y(d.y) );
/*
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(data[0].dx) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.y); });
*/
fill(255);
textAlign(CENTER);
text(formatCount(d.y), x(data[0].dx) / 2, -2, x(data[0].dx), 20 );
pop();
/*
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
*/
// N/A in p5.js.
}
}
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.4.5/p5.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment