Skip to content

Instantly share code, notes, and snippets.

@AndriiShtoiko
Created November 7, 2018 06:19
Show Gist options
  • Save AndriiShtoiko/ac809948d9088518e03e53bcd6a153c3 to your computer and use it in GitHub Desktop.
Save AndriiShtoiko/ac809948d9088518e03e53bcd6a153c3 to your computer and use it in GitHub Desktop.
bar chart scale
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body {
margin:0;
position:fixed;
top:0;
right:0;
bottom:0;
left:0;
}
.bordered {
border: 1px solid #999
}
.margin-div {
margin: 20px 0;
}
</style>
</head>
<body>
<div>
<svg id='svg'/>
</div>
<script>
// NEW LESSON *************************************************
setTimeout(() => {
let city = 'San Francisco';
let width = 700;
let height = 300;
let margin = {
top: 20,
bottom: 20,
left: 20,
right: 20,
};
let svg = d3.select('svg')
.attr('class', 'bordered')
.attr('height', height)
.attr('width', width)
// Generate dummy data ****************
let months = 6;
let days;
let data = [];
while (months > 0) {
days = 30;
while(days > 0) {
data.push({
date: new Date('2018-' + months + '-' + days),
[city]: Math.round(35 * Math.random()) + 15
})
--days
}
--months
}
// console.log(data);
// Finish Generate dummy data *********
// scalse
let xExtent = d3.extent(data, d => d.date)
// console.log(xExtent);
let xScale = d3.scaleTime()
.domain(xExtent)
.range([margin.left, width - margin.right]);
let yMax = d3.max(data, d=> d[city]);
let yExtent = d3.extent(data, d=> d[city]);
// console.log(yExtent);
let yScale = d3.scaleLinear()
.domain([0, yMax])
.range([height - margin.bottom, margin.top])
// console.log(yScale(25))
let heightScale = d3.scaleLinear()
.domain([0, yMax])
.range([0, height - margin.top - margin.bottom])
let rect = svg.selectAll('rect')
.data(data)
.enter().append('rect')
.attr('width', 2)
.attr('height', d => heightScale(d[city]))
.attr('x', d => xScale(d.date))
.attr('y', d => yScale(d[city]))
.attr('fill', 'blue')
.attr('stroke', '#fff')
// let line = d3.line()
// .x(d => xScale(d.date))
// .y(d => yScale(d[city]))
// .curve(d3.curveStep)
// svg.append('path')
// .attr('d', line(data))
// .attr('fill', 'none')
// .attr('stroke', 'blue')
let xAxis = d3.axisBottom()
.scale(xScale)
let yAxis = d3.axisLeft()
.scale(yScale)
svg.append('g')
.attr('transform', 'translate('+[0, height - margin.bottom]+')')
.call(xAxis)
svg.append('g')
.attr('transform', 'translate('+[margin.left, 0]+')')
.call(yAxis)
}, 10)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment