Published
Edited
Jan 20, 2021
Importers
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3
.create("svg") //.attr("viewBox", [0, 0, width, height]);
.attr("width", width)
.attr("height", height);

const lg = svg
.append("defs")
.append("linearGradient") // linear gradient
.attr("id", `mygrad-${inputs.id}`)
.attr("x1", "0%")
.attr("x2", "0%")
.attr("y1", "0%")
.attr("y2", "100%");

lg.append("stop")
.attr("offset", "0%")
.style("stop-color", inputs.areaColor)
.style("stop-opacity", 0);

lg.append("stop")
.attr("offset", "100%")
.style("stop-color", inputs.areaColor)
.style("stop-opacity", 0);

svg
.append("path")
.datum(data)
.style("fill", `url(#mygrad-${inputs.id})`)
.attr("d", area);

svg
.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", inputs.color)
.attr("stroke-width", 2)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("d", line);

if (inputs.mark) {
svg
.append('line')
.classed('y', true)
.attr('x1', x(d3.timeParse("%Y-%m-%d")(inputs.mark)))
.attr('x2', x(d3.timeParse("%Y-%m-%d")(inputs.mark)))
.attr('y1', margin.top)
.attr('y2', height - margin.bottom)
.attr("stroke", "rgba(255,0,0,0.25)")
.attr("stroke-width", "5px")
.style('fill', 'none');
if (inputs.markText) {
svg
.append('text')
.attr('x', x(d3.timeParse("%Y-%m-%d")(inputs.mark)) + 5)
.attr('y', margin.top)
.text(inputs.markText);
}
}

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

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

return svg.node();
}
Insert cell
height = width * inputs.heightWidthRatio
Insert cell
width = inputs.width
Insert cell
margin = ({ top: 20, right: 20, bottom: 30, left: 40 })
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
Insert cell
y = d3
.scaleLinear()
.domain([
inputs.nonzeroMinY ? d3.min(data, d => d.value) : 0,
d3.max(data, d => d.value)
])
.nice()
.range([height - margin.bottom, margin.top])
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
Insert cell
yAxis = g =>
g
.attr("transform", `translate(${margin.left},0)`)
.call(
d3.axisLeft(y).tickFormat(d => {
return d3
.format(inputs.yAxisFormat)(d)
.replace('G', 'B');
})
)
.call(g => g.select(".domain").remove())
.call(g =>
g
.select(".tick:last-of-type text")
.clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(inputs.title)
)
Insert cell
y.domain()
Insert cell
area = d3
.area()
.curve(curve)
.x(d => x(d.date))
.y0(inputs.nonzeroMinY ? y(y.domain()[0]) : y(0))
.y1(d => y(d.value))
Insert cell
Insert cell
curve = d3.curveCardinal.tension(0.8)
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