Published
Edited
Apr 21, 2020
Importers
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.create("svg").attr("viewBox", [0, 0, width, height]);

svg
.append("g")
.selectAll("g")
.data(series)
.join("g")
.attr("fill", d => color(d.key))
.selectAll("rect")
.data(d => d)
.join("rect")
.attr("x", (d, i) => x(d.data.Date))
.attr("y", d => y(d[1]))
.attr("height", d => y(d[0]) - y(d[1]))
.attr("width", x.bandwidth())
.append("title")
.text(
d => `${d.data.Date} ${d.key}
${formatValue(d.data[d.key])}`
);

svg
.append("g")
.call(xAxis)
.attr("font-weight", function(d, i) {
return i * 100 + 100;
});

svg.append("g").call(yAxis);

return svg.node();
}
Insert cell
RawData = d3.csvParse(
await FileAttachment("RechargeBySite@2.csv").text(),
(d, i, columns) => (d3.autoType(d), (d.total = d3.sum(columns, c => d[c])), d)
)
Insert cell
DataFilter = RawData.map(function(d) {
return SiteFilter == "" ? d : { Date: d.Date, [SiteFilter]: d[SiteFilter] };
})
Insert cell
ColVals = RawData.columns
Insert cell
SliceVal = 50
Insert cell
data = DataFilter.slice(17, SliceVal)
Insert cell
series = d3
.stack()
.keys(ColVals.slice(1))(data)
.map(d => (d.forEach(v => (v.key = d.key)), d))
Insert cell
SiteFilter = ""
Insert cell
timeScale = d3
.scaleTime()
.domain([new Date(2016, 2, 1), new Date(2019, 9, 15)])
.range([0, 1094])
Insert cell
new Date(2016, 2, 1)
Insert cell
getDateArray(new Date(2014, 10, 1), timeScale.invert(SliceVal))
Insert cell
getDateArray = function(start, end) {
var arr = new Array(),
dt = new Date(start);

while (dt <= end) {
arr.push(new Date(dt));
dt.setDate(dt.getDate() + 1);
}

return arr;
}
Insert cell
RawData.map(d => d.Date).slice(17)
Insert cell
x = d3
.scaleBand()
.domain(RawData.map(d => d.Date).slice(17))
.range([margin.left, width - margin.right])
.padding(0.1)
Insert cell
y = d3
.scaleLinear()
.domain([0, 120000])
.rangeRound([height - margin.bottom, margin.top])
Insert cell
color = d3
.scaleOrdinal()
.domain(series.map(d => d.key))
.range(d3.schemeSpectral[5])
.unknown("#ccc")
Insert cell
xAxis = g =>
g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(
d3
.axisBottom(x)
.tickSizeOuter(0)
.tickFormat(function(d, i) {
return (i + 9) % 12 === 0 ? d.substring(4, 8) : null;
})
)
.call(g => g.selectAll(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(null, "s"))
.call(g => g.selectAll(".domain").remove())
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more