Published
Edited
Feb 19, 2020
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
data = (await d3.csv(dataURL, d3.autoType))
//(d, i, columns)=>(d3.autoType(d), d.total = d3.sum(columns, c => d[c]), d))).sort((a,b)=>b.total-a.total)
Insert cell
Insert cell
series = d3.stack().keys(data.columns.slice(1))(data)

// series = [{"category": "fruit", "yes": 6, "no": 7, "maybe": 8},{"category": "protein", "yes": 5, "no": 9, "maybe": 12},{"category": "snack", "yes": 10, "no": 13, "maybe": 12}];
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width+margin.left+margin.right, height+margin.top+margin.bottom));
const gSvg = svg.append("g")
.attr("transform", "translate("+margin.left+","+margin.top+")");
const xScale = d3.scaleBand()
.domain(data.map(function(d){return d.category;}))
.range([0, width])
.padding(0.1);
const yScale = d3.scaleLinear()
.domain([0,d3.max(series, d => d3.max(d, d=> d[1]))])
.range([height,0]);
// const color = d3.scaleOrdinal(d3.schemeCategory10);
// const color = d3.scaleLinear().domain([1,3])
// .interpolate(d3.interpolateHcl)
// .range(["gold", "blue", "green"]);
// const color = d3.scaleLinear().range(["gold", "blue", "green"]);
var color = d3.scaleOrdinal() // D3 Version 4
.domain(["yes", "no", "maybe"])
.range(["green", "orange" , "red"]);
const rects = gSvg.selectAll("g").data(series).enter()
.append("g")
.attr("fill", d => color(d.key)); //Color is assigned here because you want everyone for the series to be the same color
rects.selectAll("rect")
.data(d => d)
.join("rect")
.attr("x", (d, i) => xScale(d.data.category))
.attr("y", d=> yScale(d[1]))
.attr("height", d=> yScale(d[0]) - yScale(d[1]))
.attr("width", xScale.bandwidth())
/*.on("mouseover", function(){d3.select(this).attr("fill", "purple")})
.on("mouseout", function(){d3.select(this).attr("fill", color(series.key))})*/;
const xAxis = gSvg.append("g")
.attr("id", "xAxis")
.attr("transform", "translate(0,"+height+")")
.call(d3.axisBottom(xScale));
const yAxis = gSvg.append("g")
.attr("id", "yAxis")
.call(d3.axisLeft(yScale));
return svg.node();
}
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