Public
Edited
Dec 21, 2021
2 forks
Insert cell
Insert cell
Insert cell
viewof activeFilters = Inputs.checkbox(["US cities"], {label: "Filter"})
Insert cell
filteredData = (activeFilters.includes("US cities")) ? data.filter((d) => d.location.country === 'US') : data
Insert cell
chart = BarChart(filteredData, {chartHeight: 350})
Insert cell
function BarChart(data, {
chartWidth = 800,
chartHeight = 600,
marginTop = 40,
marginBottom = 10,
marginLeft = 120,
marginRight = 20,
barHeight = 25
} = {}) {
const width = chartWidth - marginLeft - marginRight;
const height = chartHeight - marginTop - marginBottom;
// Creates sources <svg> element
const svg = d3.create("svg")
.attr('width', width + marginLeft + marginRight)
.attr('height', height + marginTop + marginBottom);

// Group used to enforce margin
const g = svg.append('g').attr('transform', `translate(${marginLeft},${marginTop})`);

// Scales setup
const xScale = d3.scaleLinear().range([0, width]).domain([0, d3.max(data, (d) => d.temperature)]);
const yScale = d3.scaleBand().rangeRound([0, height]).paddingInner(0.1).domain(data.map((d) => d.location.city));

// Axis setup
const xAxis = d3.axisTop().scale(xScale);
g.append('g').attr('class','x axis').call(xAxis);
const yAxis = d3.axisLeft().scale(yScale);
g.append('g').attr('class','y axis').call(yAxis);
// Render the chart with new data

// DATA JOIN use the key argument for ensurign that the same DOM element is bound to the same data-item
const rect = g.selectAll('rect').data(data, (d) => d.location.city).join(
// ENTER
// new elements
(enter) => {
const rect_enter = enter.append('rect').attr('x', 0);
rect_enter.append('title');
return rect_enter;
},
// UPDATE
// update existing elements
(update) => update,
// EXIT
// elements that aren't associated with data
(exit) => exit.remove()
);

// ENTER + UPDATE
// both old and new elements
rect.transition()
.attr('height', yScale.bandwidth())
.attr('width', (d) => xScale(d.temperature))
.attr('y', (d) => yScale(d.location.city));

rect.select('title').text((d) => d.location.city);
return svg.node();
}
Insert cell
<style>
rect {
fill: steelblue;
fill-opacity: 0.8;
}
rect:hover {
fill-opacity: 1;
}
.axis {
font-size: smaller;
}
</style>
Insert cell
data = FileAttachment("weather.json").json()
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more