Skip to content

Instantly share code, notes, and snippets.

@GitNoise
Last active June 16, 2020 07:57
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 GitNoise/d7c53a678d701f107cc185f649bfc90d to your computer and use it in GitHub Desktop.
Save GitNoise/d7c53a678d701f107cc185f649bfc90d to your computer and use it in GitHub Desktop.
Rough Radar Chart
height: 600
license: mit
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/ >
<title>Smoothed D3.js Radar Chart</title>
<!-- Google fonts -->
<link href='http://fonts.googleapis.com/css?family=Open+Sans:400,300' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>
<!-- D3.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.6/d3.min.js" charset="utf-8"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rough.js/3.1.0/rough.js"/></script>
<style>
.radarChart {
font-family: 'Open Sans', sans-serif;
font-size: 11px;
font-weight: 300;
fill: #242424;
text-align: center;
text-shadow: 0 1px 0 #fff, 1px 0 0 #fff, -1px 0 0 #fff, 0 -1px 0 #fff;
cursor: default;
}
.legend {
fill: #333333;
}
.gridCircle {
stroke: #222;
opacity: 0.5;
fill: none;
}
path {
stroke: #222;
stroke-opacity: 0.6;
}
.charts {
display: flex;
}
.axisLabel {
display:none;
}
.legend {
font-family: Comic Sans MS;
font-size: 14px;
alignment-baseline: middle;
fill-opacity: 0.9;
}
</style>
</head>
<body>
<div class="charts">
<div class="radarChart1"></div>
<div class="radarChart2"></div>
</div>
<script src="radarChart.js"></script>
<script>
d3.selection.prototype.moveToFront = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
};
/**** Set-Up ****/
var margin = {top: 100, right: 100, bottom: 100, left: 100},
width = 500 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom - 20;
/**** Data ****/
const a = 100;
var data = [
[
{axis:"Visualization design",value:0/a},
{axis:"Storytelling",value:25/a},
{axis:"Data Analysis and Data Cleaning",value:50/a},
{axis:"Tools",value:75/a},
{axis:"Presentation skills",value:100/a},
],
[
{axis:"Front-end",value:0/a},
{axis:"User Experience",value:25/a},
{axis:"Architecture",value:50/a},
{axis:"Testing/Debugging",value:75/a},
{axis:"Back-end",value:100/a},
],
];
/*** Draw the Chart ***/
var color1 = d3.scale.ordinal()
.range(["#EDC951"]);
var radarChartOptions1 = {
w: width,
h: height,
margin: margin,
maxValue: 1,
levels: 4,
roundStrokes: true,
color: color1,
labelFactor: 1.5
};
var color2 = d3.scale.ordinal()
.range(["#CC333F"]);
var radarChartOptions2 = {
w: width,
h: height,
margin: margin,
maxValue: 1,
levels: 4,
roundStrokes: true,
color: color2,
labelFactor: 1.45
};
//Call function to draw the Radar chart
RadarChart(".radarChart1", [data[0]], radarChartOptions1);
RadarChart(".radarChart2", [data[1]], radarChartOptions2);
/*** MAKE IT ROUGH! ***/
const rc = rough.svg(d3.select('svg').node());
// paths to rough paths
const allPaths = d3.selectAll('path')
allPaths.each(function(d, i) {
const aPath = d3.select(this);
const container = d3.select(this.parentNode);
const rPath = rc.path(aPath.attr('d'), {fill: i === 0 ? '#22fc6e' : '#fc6e22', fillStyle: 'cross-hatch', fillWeight: 0.2});
container.node().appendChild(rPath);
aPath.remove();
})
// circle to rough circle
const allCircles = d3.selectAll('circle')
allCircles.each(function() {
const aCircle = d3.select(this);
const container = d3.select(this.parentNode);
container.classed('circle', true);
let options = { fill: '#fff', fillStyle: 'solid' };
const rCircle = rc.circle(
+aCircle.attr("cx"),
+aCircle.attr("cy"),
+aCircle.attr("r")*2,
options);
container.node().appendChild(rCircle);
aCircle.remove();
})
// lines to rough lines
const allLines = d3.selectAll('line')
allLines.each(function() {
const aLine = d3.select(this);
const container = d3.select(this.parentNode);
const rLine = rc.line(
+aLine.attr("x1"),
+aLine.attr("y1"),
+aLine.attr("x2"),
+aLine.attr("y2"));
container.node().appendChild(rLine);
aLine.remove();
})
d3.selectAll('.axis')
.moveToFront();
</script>
</body>
</html>
/////////////////////////////////////////////////////////
/////////////// The Radar Chart Function ////////////////
/////////////// Written by Nadieh Bremer ////////////////
////////////////// VisualCinnamon.com ///////////////////
/////////// Inspired by the code of alangrafu ///////////
/////////////////////////////////////////////////////////
function RadarChart(id, data, options) {
var cfg = {
w: 600, //Width of the circle
h: 600, //Height of the circle
margin: {top: 20, right: 20, bottom: 20, left: 20}, //The margins of the SVG
levels: 3, //How many levels or inner circles should there be drawn
maxValue: 0, //What is the value that the biggest circle will represent
labelFactor: 1.25, //How much farther than the radius of the outer circle should the labels be placed
wrapWidth: 60, //The number of pixels after which a label needs to be given a new line
opacityArea: 0.2, //The opacity of the area of the blob
dotRadius: 8, //The size of the colored circles of each blog
strokeWidth: 2, //The width of the stroke around each blob
roundStrokes: false, //If true the area and stroke will follow a round path (cardinal-closed)
color: d3.scale.category10() //Color function
};
//Put all of the options into a variable called cfg
if('undefined' !== typeof options){
for(var i in options){
if('undefined' !== typeof options[i]){ cfg[i] = options[i]; }
}//for i
}//if
//If the supplied maxValue is smaller than the actual one, replace by the max in the data
var maxValue = Math.max(cfg.maxValue, d3.max(data, function(i){return d3.max(i.map(function(o){return o.value;}))}));
var allAxis = (data[0].map(function(i, j){return i.axis})), //Names of each axis
total = allAxis.length, //The number of different axes
radius = Math.min(cfg.w/2, cfg.h/2), //Radius of the outermost circle
Format = d3.format('%'), //Percentage formatting
angleSlice = Math.PI * 2 / total; //The width in radians of each "slice"
//Scale for the radius
var rScale = d3.scale.linear()
.range([0, radius])
.domain([0, maxValue]);
/////////////////////////////////////////////////////////
//////////// Create the container SVG and g /////////////
/////////////////////////////////////////////////////////
//Remove whatever chart with the same id/class was present before
d3.select(id).select("svg").remove();
//Initiate the radar chart SVG
var svg = d3.select(id).append("svg")
.attr("width", cfg.w + cfg.margin.left + cfg.margin.right)
.attr("height", cfg.h + cfg.margin.top + cfg.margin.bottom)
.attr("class", "radar"+id);
//Append a g element
var g = svg.append("g")
.attr("transform", "translate(" + (cfg.w/2 + cfg.margin.left) + "," + (cfg.h/2 + cfg.margin.top) + ")");
/////////////////////////////////////////////////////////
////////// Glow filter for some extra pizzazz ///////////
/////////////////////////////////////////////////////////
//Filter for the outside glow
var filter = g.append('defs').append('filter').attr('id','glow'),
feGaussianBlur = filter.append('feGaussianBlur').attr('stdDeviation','2.5').attr('result','coloredBlur'),
feMerge = filter.append('feMerge'),
feMergeNode_1 = feMerge.append('feMergeNode').attr('in','coloredBlur'),
feMergeNode_2 = feMerge.append('feMergeNode').attr('in','SourceGraphic');
/////////////////////////////////////////////////////////
/////////////// Draw the Circular grid //////////////////
/////////////////////////////////////////////////////////
//Wrapper for the grid & axes
var axisGrid = g.append("g").attr("class", "axisWrapper");
//Draw the background circles
axisGrid.selectAll(".levels")
.data(d3.range(1,(cfg.levels+1)).reverse())
.enter()
.append("circle")
.attr("class", "gridCircle")
.attr("r", function(d, i){return radius/cfg.levels*d;})
//Text indicating at what % each level is
axisGrid.selectAll(".axisLabel")
.data(d3.range(1,(cfg.levels+1)).reverse())
.enter().append("text")
.attr("class", "axisLabel")
.attr("x", 4)
.attr("y", function(d){return -d*radius/cfg.levels;})
.attr("dy", "0.4em")
.text(function(d,i) { return Format(maxValue * d/cfg.levels); });
/////////////////////////////////////////////////////////
//////////////////// Draw the axes //////////////////////
/////////////////////////////////////////////////////////
//Create the straight lines radiating outward from the center
var axis = axisGrid.selectAll(".axis")
.data(allAxis)
.enter()
.append("g")
.attr("class", "axis");
//Append the lines
axis.append("line")
.attr("x1", 0)
.attr("y1", 0)
.attr("x2", function(d, i){ return rScale(maxValue*1.1) * Math.cos(angleSlice*i - Math.PI/2); })
.attr("y2", function(d, i){ return rScale(maxValue*1.1) * Math.sin(angleSlice*i - Math.PI/2); })
.attr("class", "line")
function yLabelPosition(d, i){ return rScale(maxValue * cfg.labelFactor) * Math.sin(angleSlice*i - Math.PI/2) };
//Append the labels at each axis
axis.append("text")
.attr("class", "legend")
.attr("text-anchor", "middle")
.attr("dy", (d, i) => yLabelPosition(d,i) < (cfg.h/2) ? "0em" : '-2em')
.attr("x", function(d, i){ return rScale(maxValue * cfg.labelFactor) * Math.cos(angleSlice*i - Math.PI/2); })
.attr("y", yLabelPosition )
.text(function(d){return d})
.call(wrap, cfg.wrapWidth);
/////////////////////////////////////////////////////////
///////////// Draw the radar chart blobs ////////////////
/////////////////////////////////////////////////////////
//The radial line function
var radarLine = d3.svg.line.radial()
.interpolate("linear-closed")
.radius(function(d) { return rScale(d.value); })
.angle(function(d,i) { return i*angleSlice; });
if(cfg.roundStrokes) {
radarLine.interpolate("cardinal-closed");
}
//Create a wrapper for the blobs
var blobWrapper = g.selectAll(".radarWrapper")
.data(data)
.enter().append("g")
.attr("class", "radarWrapper");
//Append the backgrounds
blobWrapper
.append("path")
.attr("class", "radarArea")
.attr("d", function(d,i) { return radarLine(d); })
.style("fill", function(d,i) { return cfg.color(i); })
.style("fill-opacity", cfg.opacityArea)
//Create the outlines
blobWrapper.append("path")
.attr("class", "radarStroke")
.attr("d", function(d,i) { return radarLine(d); })
.style("stroke-width", cfg.strokeWidth + "px")
.style("stroke", function(d,i) { return cfg.color(i); })
.style("fill", "none")
.style("filter" , "url(#glow)");
//Append the circles
blobWrapper.selectAll(".radarCircle")
.data(function(d,i) { return d; })
.enter().append("circle")
.attr("class", "radarCircle")
.attr("r", cfg.dotRadius)
.attr("cx", function(d,i){ return rScale(d.value) * Math.cos(angleSlice*i - Math.PI/2); })
.attr("cy", function(d,i){ return rScale(d.value) * Math.sin(angleSlice*i - Math.PI/2); })
.style("fill", function(d,i,j) { return cfg.color(j); })
.style("fill-opacity", 0.8);
/////////////////////////////////////////////////////////
/////////////////// Helper Function /////////////////////
/////////////////////////////////////////////////////////
//Taken from http://bl.ocks.org/mbostock/7555321
//Wraps SVG text
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.4, // ems
y = text.attr("y"),
x = text.attr("x"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", x).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}//wrap
}//RadarChart
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment