<div class="chart"></div>
<svg width="0" height="0">
<defs>
<pattern id="dots" x="0" y="0" width="3" height="3" patternUnits="userSpaceOnUse">
<rect fill="#5D92F6" x="0" y="0" width="3" height="3"></rect>
<circle fill="#11419B" cx="1" cy="1" r="1">
</circle>
</pattern>
<pattern id="lines" x="0" y="0" width="3" height="3" patternUnits="userSpaceOnUse">
<rect fill="#F06B5A" x="0" y="0" width="3" height="3"></rect>
<rect fill="#B91919" x="0" y="0" width="3" height="1"></rect>
</pattern>
</defs>
</svg>
body {
background-color: #F6F6FC;
}
.chart {
width: 700px;
height: 450px;
margin: 60px auto 0 auto;
background-color: #fff;
border-radius: 10px;
box-shadow: 0 0 10px #D8D8E9;
}
.xTicks, .legend text {
font-family: sans-serif;
font-size: 0.65rem;
fill: #49456C;
}
.bar {
fill: #5D92F6;
fill: url(#dots)
}
.bar.danger {
fill: #F06B5A;
fill: url(#lines);
}
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]);
const legend = chart.append("g")
.attr("class", "legend")
.attr("aria-label", "Legend");
legend.append("rect")
.attr("fill", "url(#dots)")
.attr("width", 13)
.attr("height", 13)
.attr("rx", 2)
.attr("x", margin.left / 2)
.attr("y", margin.top);
legend.append("text")
.text("Over 100 daily visitors")
.attr("x", margin.left / 2 + 20)
.attr("y", margin.top + 10);
legend.append("rect")
.attr("fill", "url(#lines)")
.attr("width", 13)
.attr("height", 13)
.attr("rx", 2)
.attr("x", margin.left / 2)
.attr("y", margin.top + 30);
legend.append("text")
.text("Under 100 daily visitors")
.attr("x", margin.left / 2 + 20)
.attr("y", margin.top + 40);
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.