Skip to content

Instantly share code, notes, and snippets.

@pebblexe
Last active January 17, 2017 17:20
Show Gist options
  • Save pebblexe/b5e94eee3f0b35a601732371511ec460 to your computer and use it in GitHub Desktop.
Save pebblexe/b5e94eee3f0b35a601732371511ec460 to your computer and use it in GitHub Desktop.
the chart replicates with only axes, missing value line
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.4.1/d3.js"></script>
<div class="panel panel-primary">
<div class="panel-heading"><strong>Activity Per Unit</strong></div>
<div class="panel-body">
<div class="chart0"></div>
</div>
</div>
<div class="panel panel-primary">
<div class="panel-heading"><strong>Activity Per Unit</strong></div>
<div class="panel-body">
<div class="chart0"></div>
</div>
</div>
<script>
var data = { "studyGuide":{
"count":20,
"avgTime":"4 minutes and 32 seconds",
"unitCount": [
{"name":"welcome","count":3},
{"name":"1","count":10},
{"name":"2","count":5},
{"name":"3","count":12},
{"name":"4","count":15},
{"name":"5","count":2},
{"name":"6","count":7}
]
}};
var dataParsed = data['studyGuide']['unitCount'];
// set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 550 - margin.left - margin.right,
height = 550 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// define the line
var valueline = d3.line()
.x(function(d) { return x(d.name); })
.y(function(d) { return y(d.count); });
// append the svg obgect to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.selectAll(".chart0").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var tryParse = function(i) {
if(i === "welcome") {
return 0;
}
else {
return +i;
}
}
// format the data
dataParsed.forEach(function(d) {
d.name = tryParse(d.name);
d.count = +d.count;
});
x_max = d3.max(dataParsed, function(d) { return d.name; });
// Scale the range of the data
x.domain([0, x_max]);
y.domain([0, d3.max(dataParsed, function(d) { return d.count; })]);
// Add the valueline path.
svg.append("path")
.data([dataParsed])
.attr("class", "line")
.attr("d", valueline);
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x).ticks(x_max));
// Add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(y));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment