Skip to content

Instantly share code, notes, and snippets.

@larsenmtl
Forked from pebblexe/gist:0fa48e4b10426ccf3d339b9e9060e727
Last active January 16, 2017 22:06
Show Gist options
  • Save larsenmtl/93cb0b5a5201d63e679826877406b606 to your computer and use it in GitHub Desktop.
Save larsenmtl/93cb0b5a5201d63e679826877406b606 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.scalePoint().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 + ")");
// format the data
dataParsed.forEach(function(d) {
d.count = +d.count;
});
console.log("dataParsed", dataParsed);
// Scale the range of the data
x.domain(dataParsed.map(d => 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)
.style("fill", "none")
.style("stroke", "steelblue")
.style("stroke-width", "2px");
// 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