Public
Edited
May 1
Insert cell
Insert cell
Insert cell
data = [
{ letter: "A", frequency: 0.08167 },
{ letter: "B", frequency: 0.01492 },
{ letter: "C", frequency: 0.02782 },
{ letter: "D", frequency: 0.04253 },
{ letter: "E", frequency: 0.12702 },
{ letter: "F", frequency: 0.02288 },
{ letter: "G", frequency: 0.02015 },
{ letter: "H", frequency: 0.06094 },
{ letter: "I", frequency: 0.06966 },
{ letter: "J", frequency: 0.00153 }
];
Insert cell
Insert cell
viewof order = {
const select = Inputs.select(
new Map([
["Alphabetical", (a, b) => a.letter.localeCompare(b.letter)],
["Frequency Ascending", (a, b) => a.frequency - b.frequency],
["Frequency Descending", (a, b) => b.frequency - a.frequency]
]),
{ label: "Order" }
);
return select;
}
Insert cell
Insert cell
chart = {
// Specify the chart’s dimensions.
const width = 640;
const height = 400;
const marginTop = 20;
const marginRight = 0;
const marginBottom = 30;
const marginLeft = 40;

// Define color settings, feel free to modify
const colorDefault = "steelblue";
const colorHighlight = "orange";
// Declare the x (horizontal position) scale and the corresponding axis generator.
const scaleX = d3.scaleBand()
.domain(data.map(element => element.letter))
.range([marginLeft, width - marginRight])
.padding(0.1);
const xAxis = d3.axisBottom(scaleX).tickSizeOuter(0);

// Declare the y (vertical position) scale.
const scaleY = d3.scaleLinear()
.domain([0, d3.max(data, element => element.frequency)]).nice()
.range([height - marginBottom, marginTop]);

// Create the SVG container.
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
// .attr("style", `max-width: ${width}px; height: auto; font: 10px sans-serif; overflow: visible;`)
.style("max-width", (width) + "px")
.style("height", "auto")
.style("font", "10px sans-serif")
.style("overflow", "visible");

// Define tooltip selector
// TODO: Append tooltip style definition after append("div")
// Styles you may want to use: background, border, padding, etc.
// Remember to set div invisible and make position absolute for default
const tooltip = d3.select("body").append("div")
.style('display', 'none')
.style('position', 'absolute')
.style('background-color', 'white')
.style('border', '2px solid black')
.style('padding', '3px')
.style('pointer-events', 'none');

// Create a bar for each letter.
// TODO: 1. Add tooltip functionalities
// 2. Add an hover and on-click highlight color change to bars
const bar = svg.append("g")
.attr("fill", colorDefault)
.selectAll("rect")
.data(data)
.join("rect")
.style("mix-blend-mode", "multiply") // Darker color when bars overlap during the transition.
// x-axis position of bar center from left. scaleX(d.letter) gets position of x-axis ticks.
.attr("x", (element) => scaleX(element.letter))
// y-axis position of bar top from top. scaleY(d.frequency) gets frequency value
.attr("y", (element) => scaleY(element.frequency))
// amount from graph top to bottom - y position offset
.attr("height", (element) => (scaleY(0) - scaleY(element.frequency)))
.attr("width", scaleX.bandwidth())
// Add your code for the tooltip and on-click after .attr("width", scaleX.bandwidth())
// Function you will use .on(eventType, listenerFunction)
// Tooltip: "mouseover", "mousemove", and "mouseout" functionalities
// On mouseover, set the bar color to highlight color, set the tooltip to visible and define position, and display image
// what image???
// Tooltip message can be defined by .html(`YOUR MESSAGE`)
// selector of the current bar can be defined by bar = d3.select(this)
.on('mouseover', function(event,d){
const thisBar = d3.select(this)
.attr("fill", colorHighlight);
tooltip
.html("tooltip message")
.style('display', 'block')
.attr("x", (event.pageX + 1));
})
// On mousemove, update the tooltip position
.on('mousemove', (event) => {
tooltip
.style('left', (event.pageX + 1) + 'px')
.style('top', (event.pageY - 35) + 'px');
})
// On mouseout, set tooltip back to invisible, if the bar is not clicked, reset color
.on('mouseout', function(){
const thisBar = d3.select(this);

if(!thisBar.classed("clicked")){
thisBar.attr("fill", colorDefault);
}
tooltip
.style('display', 'none');
})
// On-click event: "click", set the color to highlight color
// Use bar = d3.select(this) and bar.classed("clicked", bar.classed("clicked")) to select clicked/unclicked bars
.on('click', function(){
const thisBar = d3.select(this);
thisBar.classed("clicked", !thisBar.classed("clicked"));
// reminder: cannot use a variable inside of its own .() chain
});

// Create the axes.
const gx = svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(xAxis);
const gy = svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(scaleY).tickFormat((y) => (y * 100).toFixed()))
.call(g => g.select(".domain").remove());

function update(order) {
// Get selected ordered data mapping
scaleX.domain(data.sort(order).map(element => element.letter));

// TODO: Add animation to bars before setting new x positions of bars (.attr("x", d => x(d.letter)))
// Function you may need:
// trainsition(): normalizes the start and end values, and calculates all their in-between states
// duration(): set the duration of animation, let's set to 750 for the bar, feel free to explore
// delay(): set delays to objects, we can add a stagger effect to the bars
bar.data(data, element => element.letter).order() // movees data based on the selected order type
.transition()
.duration(750) // in ms
// .delay((element,i) => (i*20))
.attr("x", element => scaleX(element.letter));

// TODO: Add a similar animation to x ticks before changing ticks (before .call(xAxis))
gx
.transition()
.duration(750)
// .delay((element,i) => (i*20))
.call(xAxis).selectAll(".tick");

};

// Return the chart, with an update function that takes as input a domain
// comparator and transitions the x axis and bar positions accordingly.
return Object.assign(svg.node(), {update});
}
Insert cell
update = chart.update(order)
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