Published
Edited
Oct 13, 2020
Insert cell
Insert cell
Insert cell
scaleBand = {
return d3
.scaleBand()
.domain(categories)
.range([0, 60]);
}
Insert cell
Insert cell
viewof select = DOM.select(categories)
Insert cell
Insert cell
scaleBand(select)
Insert cell
Insert cell
// make an array of objects with colors and random heights for easy d3 handline
data = [
{
color: "red",
height: 50
},
{
color: "blue",
height: 280
},
{
color: "green",
height: 200
}
]
Insert cell
simple_bar_chart = {
const svg = d3
.create('svg')
.attr('width', 500)
.attr('height', 300);

const yScale = d3.scaleLinear().range([30, 270]); // leave a margin of 30 on top and bottom
const yAxis = d3.axisLeft().scale(yScale);

// append y-axis
svg
.append('g')
.call(yAxis)
.attr('transform', 'translate(30,0)'); // shift y-axis left 30

// UNCOMMENT THIS WHEN YOU REACH THIS SECTION
scaleBand.range([30, 270]); // update range for scaleBand to match our svg dimensions

// ANSWER FOR PADDINGiNNER
//scaleBand.paddingInner(0.2);

const xAxis = d3.axisBottom().scale(scaleBand);

svg
.append('g')
.call(xAxis)
.attr('transform', 'translate(0, 270)');

svg
.selectAll('.bar')
.data(data)
.join(enter => enter.append("rect"))
.attr('x', d => scaleBand(d.color))
.attr('y', d => yScale(d.height))
.attr('width', scaleBand.bandwidth())
.attr('height', d => yScale(0) - yScale(d.height))
.attr('fill', d => d.color);

return svg.node();
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
sortedArr = {
const arr = [9, 2, 4, 21, 42, 68];

// you might notice this looks like a compareTo function in Java
function compare(a, b) {
if (a < b) {
return -1;
} else if (a == b) {
return 0;
} else {
// b > a
return 1;
}
}

return arr.sort(compare);
}
Insert cell
Insert cell
descending_sort_compare = (a, b) => b - a
Insert cell
Insert cell
data.sort((a, b) => b.height - a.height)
Insert cell
Insert cell
d3 = require('d3@5')
Insert cell
import {
render_data_table,
table_styles,
displayImage,
displayCaution
} from '@info474/utilities'
Insert cell
html`<style>
p code, li > code {color: #c30771;}
</style>
`
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