Skip to content

Instantly share code, notes, and snippets.

@anosikeosifo
Last active September 9, 2017 14:13
Show Gist options
  • Save anosikeosifo/a6a9e5b60684dcb4f7642314e7c204e4 to your computer and use it in GitHub Desktop.
Save anosikeosifo/a6a9e5b60684dcb4f7642314e7c204e4 to your computer and use it in GitHub Desktop.
Histogram Demo
license: mit
body {
margin: 0;
padding: 0;
background-color: #ccc;
padding: 5em;
}
#work__area {
width: 100%;
background-color: #efefef;
border-radius: 5px;
}
#chart-area {
height: 450px;
padding: 20px 50px;
}
#header__title {
text-align: center;
}
svg {
width: 100%;
height: 100%;
}
.rect__hist:hover {
cursor: pointer;
fill: #ffa600;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3.js Frontend Masters - Intro Histogram</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<section id="work__area">
<h3 id="header__title">D3 Histogram Demo</h3>
<div id='chart-area'>
<svg>
</svg>
</div>
</section>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="index.js" charset="utf-8"></script>
</body>
</html>
const chartData = [120, 400, 250, 205, 80, 230];
const rectWidth = 50;
const height = 400;
const svg = d3.select("svg");
var enter = svg
.selectAll("rect")
.data(chartData)
.enter()
.append("rect")
.attr("transform", "translate(50, 0)")
.attr("x", (d, i) => i * rectWidth)
.attr("y", d => height - d)
.attr("width", rectWidth)
.attr("height", d => d)
.attr("fill", "teal")
.attr("stroke", "#fff")
.attr("class", "rect__hist");
//append yAxis
// // // // //
const yScale = d3
.scaleLinear()
.domain(d3.extent(chartData))
.range([height, 0]);
const yAxis = d3.axisLeft().scale(yScale);
yAxis.ticks(10, ",.0f");
// yAxis.tickFormat(d3.format(",.0f"));
const axis = d3
.select("svg")
.append("g")
.attr("transform", "translate(30, 0)")
// .attr("stroke", "red")
.call(yAxis);
const axisText = axis
.selectAll("text")
.attr("fill", d => (d > 200 ? "red" : "green"));
console.log("yAxis===> ", axis.node());
// console.log("extent===>>", d3.extent(enter.data()));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment