Skip to content

Instantly share code, notes, and snippets.

@pebblexe
Last active January 16, 2017 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pebblexe/0fa48e4b10426ccf3d339b9e9060e727 to your computer and use it in GitHub Desktop.
Save pebblexe/0fa48e4b10426ccf3d339b9e9060e727 to your computer and use it in GitHub Desktop.
trying to create x axis
<!DOCTYPE html>
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="chart0"></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 = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// set the ranges
var x = d3.scaleTime().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.select("#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;
});
console.log("dataParsed", dataParsed);
// Scale the range of the data
x.domain(d3.extent(dataParsed, function(d) { return d.name; }));
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("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment