Public
Edited
May 1, 2023
Insert cell
md`# D3v4 Animated Bar Chart with Tooltip - Changing to vertical`
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, height, width]);
const rect = svg
.selectAll('g')
.data(data)
.enter()
.append('rect')
.attr('fill', staticColor)
.attr('y', (d, i) => y(d.country))
.attr('height', y.bandwidth())
.attr('x', d => x(0))
.attr('width', d => width )
.on('mouseover', function (d, i) {
tooltip
.html(
`<div>Country: ${d.country}</div><div>Value: ${d.value}</div>`
)
.style('visibility', 'visible');
d3.select(this).transition().attr('fill', hoverColor);
})
.on('mousemove', function () {
tooltip
.style('top', d3.event.pageY - 10 + 'px')
.style('left', d3.event.pageX + 10 + 'px');
})
.on('mouseout', function () {
tooltip.html(``).style('visibility', 'hidden');
d3.select(this).transition().attr('fill', staticColor);
});
rect
.transition()
.ease(d3.easeLinear)
.duration(800)
.attr('x', d => x(d.value))
.attr('width', d => width - x(d.value))
.delay((d, i) => i * 100);

return svg.node();
}
Insert cell
width = 400
Insert cell
height = 200
Insert cell
margin = ({top: 20, right: 30, bottom: 30, left: 40})
Insert cell
rawData = [
{
country: 'United States',
value: 12394
},
{
country: 'Russia',
value: 6148
},
{
country: 'Germany (FRG)',
value: 8653
},
{
country: 'France',
value: 7162
},
{
country: 'United Kingdom',
value: 9214
},
{
country: 'China',
value: 4131
},
{
country: 'Spain',
value: 2814
},
{
country: 'Netherlands',
value: 3167
},
{
country: 'Italy',
value: 1660
},
{
country: 'Israel',
value: 1263
}
]
Insert cell
data = sort(rawData);
Insert cell
staticColor = "#437c90"
Insert cell
hoverColor = "#eec42d"
Insert cell
tooltip = d3
.select('body')
.append('div')
.attr('class', 'd3-tooltip')
.style('position', 'absolute')
.style('z-index', '10')
.style('visibility', 'hidden')
.style('padding', '10px')
.style('background', 'rgba(0,0,0,0.6)')
.style('border-radius', '4px')
.style('color', '#fff')
.text('a simple tooltip');
Insert cell
y = d3
.scaleBand()
.range([0, width])
.domain(data.map(d => d.country))
.padding(0.2);
Insert cell
x = d3
.scaleLinear()
.domain([0, d3.max(data, d => d.value)])
.range([height, 0]);
Insert cell
sort = (data) => data.sort((a, b) => d3.ascending(a.value, b.value));
Insert cell
d3 = require("d3@4")
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