<div class="chart"></div>
body {
background-color: #F6F6FC;
}
.chart {
width: 700px;
height: 450px;
margin: 60px auto;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px #D8D8E9;
}
.xTicks {
font-family: sans-serif;
font-size: 0.65rem;
fill: #726F8B;
}
.bar {
fill: #5D92F6;
}
.bar.danger {
fill: #F06B5A;
}
const data = [
{day: "Mon", visitors: 100},
{day: "Tue", visitors: 174},
{day: "Wed", visitors: 92},
{day: "Thu", visitors: 193},
{day: "Fri", visitors: 103},
{day: "Sat", visitors: 104},
{day: "Sun", visitors: 294}];
const margin = {left: 50, right: 50, top: 30, bottom: 30};
const width = 700 - margin.left - margin.right;
const height = 450 - margin.top - margin.bottom;
const chart = d3.select(".chart").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
const x = d3.scaleLinear().rangeRound([0, width]);
const y = d3.scaleLinear().rangeRound([0, height]);
const maxYValue = d3.max(data, row => row.visitors) || 10;
x.domain([0, data.length]);
y.domain([maxYValue + 50, 0]);
chart.selectAll(".xTicks")
.data(data)
.enter().append("text")
.text((data) => data.day)
.attr("class", "xTicks")
.attr("x", function(row, index) { return x(index + 1) + 5; })
.attr("y", height + margin.top)
.attr("width", 30)
.attr("text-anchor", "middle");
chart.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", row => row.visitors > 100 ? "bar" : "bar danger")
.attr("x", (row, index) => x(index + 1) )
.attr("y", row => y(row.visitors) + margin.top / 2)
.attr("width", 10)
.attr("height", row => height - y(row.visitors))
.attr("rx", 5);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.