Published
Edited
Jun 19, 2019
3 forks
8 stars
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height));
let bars = svg.append("g").attr("transform", "translate(0, 0)");
createTooltip();
let categories = bars.selectAll(".bar")
.data(stackedData)
.enter()
.append("g")
.attr("class", "day")
.attr("fill", (d,i)=>colorPalette(i));

categories
.selectAll("rect")
.data(function(d) { return d; })
.enter()
.append("rect")
.attr("x", (d, i) => x(i))
.attr("y", d => {
return d[1] !== d[0] ? y(d[1]) : 0;
})
.attr("rx", "3")
.attr("ry", "3")
.attr("width", x.bandwidth())
.attr("height", d => {
return d[1] !== d[0] ? y(d[0]) - y(d[1]) : 0;
})
.on("mouseenter", (d, i, nodes) => {
let tooltip = d3.select("#tooltip");
tooltip.style("opacity", 1);
let keys = Object.keys(data[0]);
let legend = keys.map((k,i) => {
let color = colorPalette(i);
return `
<div style="margin-top:7px;margin-bottom:7px;">
<div style="border-radius:8px;display:inline;margin-top:2px;width:13px;height:13px;position:absolute;background:${color};"></div>
<div style="margin-left:22px;font-size:15px;">${k}: ${d.data[k]}</div>
</div>
`
}).reverse().join("\n");

d3.select("#tooltip-text").html(`<div>` + legend + `</div>`);

let barPos = nodes[i].getBoundingClientRect();
let tooltipWidth = tooltip.node().getBoundingClientRect().width;
tooltip
.style("left", ((barPos.x + (barPos.width / 2)) - (tooltipWidth / 2)) + "px")
.style("top", (d3.event.pageY - 160) + "px");

})
.on("mouseleave", () => {
console.log("LEAVE");
d3.select("#tooltip").style("opacity", 0);
});
return svg.node();
}
Insert cell
createTooltip = () => {
let tooltipWrapper = d3.select("body")
.append("div")
.attr("id", "tooltip")
.style("opacity", "0")
.style("pointer-events", "none")
.style("position", "absolute")
.style("transition", "all 0.1s ease-out");

tooltipWrapper.append("div")
.attr("class", "tooltip")
.attr("id", "tooltip-text")
.attr("style",
`background: #fff;
z-index: 10;
display: inline-block;
pointer-events: none;
text-align: left;
padding: 0.6em 2em;
padding-left: 7px;
padding-right: 7px;
white-space: nowrap;
font: 12px sans-serif;
background: white;
border-radius: 8px;`
);

tooltipWrapper.append("div")
.attr("style",
`position: absolute;
bottom: 0;
left: 50%;
width: 13px;
height: 13px;
background: white;
border: 1px solid #ddd;
border-top-color: transparent;
border-left-color: transparent;
transform: translate(-50%, 50%) rotate(45deg);
transform-origin: center center;
z-index: 10;`
)
}

Insert cell
Insert cell
Insert cell
Insert cell
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