Skip to content

Instantly share code, notes, and snippets.

@imothee
Created June 16, 2017 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imothee/0e0a9754ec5fb3f7091164cf947cdbc4 to your computer and use it in GitHub Desktop.
Save imothee/0e0a9754ec5fb3f7091164cf947cdbc4 to your computer and use it in GitHub Desktop.
Creating a custom chart in D3 V4
const parseDate = d3.timeParse("%Y-%m-%e");
// Get the extent of the dates in the range
const xDomain = d3.extent(Object.keys(changes), (d) => { return parseDate(d) });
const xRange = [0, width - margins.left - margins.right];
// Alogirthm to generate the circle size log scale of maxCount
const fillSize = (len) => {
if (len < 1) {
return 0;
}
let scale = Math.log(len) / Math.log(maxCount);
return parseInt(scale * 20) + 5;
};
// Create the x scale and axis
const x = d3.scaleTime()
.domain(xDomain)
.range(xRange);
const xAxis = d3.axisBottom(x)
.tickFormat(d3.timeFormat("%m/%d"))
.ticks(d3.timeDay.every(1));
// Start drawing the svg
const svg = d3.select(this.svg);
const div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
const g = svg.append('g')
.attr('class', 'axis')
.attr('transform', `translate(${margins.left}, ${height / 2})`)
.call(xAxis);
svg.append('text')
.attr('transform', `translate(0, ${margins.top + 20})rotate(90)`)
.text('Follows');
svg.append('text')
.attr('transform', `translate(0, ${height / 2 + 20})rotate(90)`)
.text('Unfollows');
const f = g.append('g')
.selectAll('circle')
.data(Object.keys(changes))
.enter()
.append('circle')
.attr('cx', (d) => { return x(parseDate(d)); })
.attr('cy', -60)
.attr('r', (d) => { return fillSize(changes[d].follows.length); })
.style('fill', '#00aced')
.on("mouseover", (d) => {
div.transition()
.duration(200)
.style("opacity", .9);
div.html(`${changes[d].follows.length} follows`)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", (d) => {
div.transition()
.duration(500)
.style("opacity", 0);
})
.on('click', (d) => {
onSelect('follow', changes[d].follows);
});
const u = g.append('g')
.selectAll('circle')
.data(Object.keys(changes))
.enter()
.append('circle')
.attr('cx', (d) => { return x(parseDate(d)); })
.attr('cy', 60)
.attr('r', (d) => { return fillSize(changes[d].unfollows.length); })
.style('fill', '#FF5312')
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div.html(`${changes[d].unfollows.length} unfollows`)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
})
.on('click', (d) => {
onSelect('follow', changes[d].follows);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment