Public
Edited
Jun 5, 2023
1 fork
Insert cell
Insert cell
title = md`
# Energy Generation Trends Across the United States
`;
Insert cell
d3 = require('d3@7')
Insert cell
energy_data = FileAttachment("energy_data.json").json()
Insert cell
output = FileAttachment("output.json").json()
Insert cell
us_json = FileAttachment("us_json.json").json()
Insert cell
nodes = Object.entries(output).map(([state, years]) => {
let node = { id: state, years: [] };
for (let [year, data] of Object.entries(years)) {
node.years.push({ year: parseInt(year), value: +data["categories"]["All Fuels"] });
}
return node;
});
Insert cell
viewof selectedYear = html`<input type="range" min="2001" max="2022" value="2001">`
Insert cell
year = md`
## ${selectedYear}
`;
Insert cell
selectedYearValue = {
return selectedYear;
}
Insert cell
debugValues = nodes.map(d => {
return {
id: d.id,
year: +selectedYear,
valueForYear: d.years.find(year => year.year === +selectedYear).value,
newSize: Math.sqrt(d.years.find(year => year.year === +selectedYear).value) / 10
};
});
Insert cell
width = 1250
Insert cell
height = 450
Insert cell
drag = simulation => {
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
updated_nodes = {
us_json.nodes.forEach(node => {
const match = debugValues.find(value => value.id.trim() === node.id);
if (match) {
node.r = match.newSize;
}
});
return us_json.nodes;
}
Insert cell
simulation = d3.forceSimulation(updated_nodes)
.force("link", d3.forceLink(us_json.links).id(d => d.id))
.force("charge", d3.forceManyBody())
.force("center", d3.forceCenter(width / 2, height / 2));
Insert cell
minRadius = d3.min(updated_nodes, d => d.r);
Insert cell
maxRadius = d3.max(updated_nodes, d => d.r);
Insert cell
colorScale = d3.scaleSequential()
.domain([minRadius, maxRadius])
.interpolator(d3.interpolatePlasma);
Insert cell
svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
Insert cell
svg.append("g")
.attr("stroke", "#999")
.attr("stroke-opacity", 0.6)
.selectAll("line")
.data(us_json.links)
.join("line")
.attr("stroke-width", d => Math.sqrt(d.value));
Insert cell
node =
svg.append("g")
.attr("stroke", "#fff")
.attr("stroke-width", 1.5)
.selectAll("circle")
.data(updated_nodes)
.join(enter => enter.append("circle")
.attr("fill", "#000")
.call(drag(simulation))
.attr("r", d => d.r)
.attr("fill", d => colorScale(d.r))
.append("title")
.text(d => `${d.id}: ${Math.round(Math.pow(d.r * 10, 2))}MWh`),
update => update,
exit => exit.remove()
);

Insert cell
simulation.on("tick", () => {
svg.selectAll("circle")
.attr("cx", d => d.x)
.attr("cy", d => d.y);

svg.selectAll("line")
.attr("x1", d => d.source.x)
.attr("y1", d => d.source.y)
.attr("x2", d => d.target.x)
.attr("y2", d => d.target.y);
});
Insert cell
map = svg.node();
Insert cell
margin = ({top: 20, right: 120, bottom: 50, left: 100})
Insert cell
state = Object.keys(energy_data)
Insert cell
viewof chosenState = {
const select = document.createElement("select");
state.forEach(e => {
const option = document.createElement("option");
option.text = e;
option.value = e;
select.add(option);
});
return select;
}
Insert cell
data2 = Object.entries(energy_data[chosenState].years).map(([year, values]) => {
let convertedValues = {};
for (let key in values) {
convertedValues[key] = +values[key];
}
return {year: +year, ...convertedValues};
})

Insert cell
stateData = energy_data[chosenState];
Insert cell
columns = Array.from(new Set(data2.flatMap(d => Object.keys(d)).filter(e => e !== "state" && e !== "year")))
Insert cell
x = d3.scaleBand()
.domain(d3.range(data2[0].year, data2[data2.length - 1].year + 1))
.range([margin.left, width1 - margin.right])
.padding(0.1)
Insert cell
xAxis = d3.axisBottom(x).tickFormat(d3.format("d"));
Insert cell
y = d3.scaleLinear()
.domain([0, d3.max(data2, e => d3.sum(columns, key => e[key] || 0))]).nice()
.range([height1 - margin.bottom, margin.top])
Insert cell
yAxis = d3.axisLeft(y)
.tickFormat(d3.format(".2s"));
Insert cell
colors = ["#778899", "#FF7F0E", "#BCBD22", "#E377C2", "#9467BD", "#32CD32","#1F77B4", "#AEC7E8", "#FFD700", "#17BECF","#7F7F7F", "#FFBB78", "#98DF8A", "#FF9896", "#C5B0D5", "#C49C94", "#F7B6D2", "#C7C7C7", "#DBDB8D", "#9EDAE5"];
Insert cell
color = d3.scaleOrdinal()
.domain(columns)
.range(colors);
Insert cell
tooltip = html`<div class="tooltip" style="opacity: 0; position: absolute; background-color: white; border: solid; border-width: 2px; border-radius: 5px; padding: 5px;"></div>`

Insert cell
selected_state = md`
## ${chosenState}
`;
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width1 + margin.right, height1]);

const tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("font-family", "'Open Sans', sans-serif")
.style("font-size", "15px")
.style("z-index", "10")
.style("background-color", "#A7CDFA")
.style("color", "#000000")
.style("border", "solid")
.style("border-color", "#000000")
.style("padding", "5px")
.style("border-radius", "2px")
.style("visibility", "hidden");

let originalData = data2;
let filteredData = data2;

const bars = svg.append("g")
.selectAll("g")
.data(d3.stack().keys(columns)(filteredData))
.join("g")
.attr("fill", e => color(e.key))
.selectAll("rect")
.data(e => e, e => e.key)
.join("rect")
.attr("x", (e, i) => x(e.data.year))
.attr("y", e => y(e[1]))
.attr("height", e => y(e[0]) - y(e[1]))
.attr("width", x.bandwidth())
.on("mouseover", (event, d) => {
const [xValue, yValue] = [d.data.year, d[1] - d[0]];
const category = d3.select(event.target.parentNode).datum().key;
tooltip.style("visibility", "visible")
.html(`Energy Sector: ${category}<br>Year: ${xValue}<br>Energy Generated: ${yValue} MWh`)
.style("left", `${event.pageX}px`)
.style("top", `${event.pageY}px`);

d3.select(event.target)
.style("opacity", 0.7)
.style("stroke", "black")
.style("stroke-width", "2px");
})
.on("mouseout", (event, d) => {
tooltip.style("visibility", "hidden");

d3.select(event.target)
.style("opacity", 1)
.style("stroke", "none");
});

svg.append("text")
.attr("x", width1 / 2)
.attr("y", height1 - margin.bottom / 100)
.attr("text-anchor", "middle")
.text("Year");

svg.append("text")
.attr("x", -height1 / 2)
.attr("y", margin.left / 3.5)
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.text("Energy Generated MWh");

const legend = svg.selectAll(".legend")
.data([...columns, "all"])
.enter()
.append("g")
.attr("class", "legend")
.attr("transform", (d, i) => `translate(120, ${i * 20})`);

legend.append("rect")
.attr("x", width1 - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", d => (d === "all" ? "gray" : color(d)));

legend.append("text")
.attr("x", width1 - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(d => (d === "all" ? "All" : d));

svg.append("g")
.attr("transform", `translate(0,${height1 - margin.bottom})`)
.call(xAxis)
.append("text")
.attr("x", width1 / 2)
.attr("y", margin.bottom / 2)
.attr("fill", "black")
.attr("text-anchor", "middle");

svg.append("g")
.attr("transform", `translate(${margin.left}, 0)`)
.call(yAxis);

return svg.node();
}

Insert cell
viewof chosenState1 = {
const select = document.createElement("select");
state.forEach(e => {
const option = document.createElement("option");
option.text = e;
option.value = e;
select.add(option);
});
return select;
}
Insert cell
stateData1 = energy_data[chosenState1];
Insert cell
data3 = Object.entries(energy_data[chosenState1].years).map(([year, values]) => {
let convertedValues = {};
for (let key in values) {
convertedValues[key] = +values[key];
}
return {year: +year, ...convertedValues};
})
Insert cell
width1 = 1250
Insert cell
height1 = 600
Insert cell
x1 = d3.scaleBand()
.domain(d3.range(data3[0].year, data3[data3.length - 1].year + 1))
.range([margin.left, width1 - margin.right])
.padding(0.1)
Insert cell
xAxis1 = d3.axisBottom(x1).tickFormat(d3.format("d"));
Insert cell
y1 = d3.scaleLinear()
.domain([0, d3.max(data3, e => d3.sum(columns, key => e[key] || 0))]).nice()
.range([height1 - margin.bottom, margin.top])
Insert cell
yAxis1 = d3.axisLeft(y1)
.tickFormat(d3.format(".2s"));
Insert cell
margin1 = ({top: 10, right: 60, bottom: 25, left: 50})
Insert cell
selected_state1 = md`
## ${chosenState1}
`;
Insert cell
chart1 = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width1 + margin.right, height1]);

const tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("font-family", "'Open Sans', sans-serif")
.style("font-size", "15px")
.style("z-index", "10")
.style("background-color", "#A7CDFA")
.style("color", "#000000")
.style("border", "solid")
.style("border-color", "#000000")
.style("padding", "5px")
.style("border-radius", "2px")
.style("visibility", "hidden");

let originalData = data3;
let filteredData = data3;

const bars = svg.append("g")
.selectAll("g")
.data(d3.stack().keys(columns)(filteredData))
.join("g")
.attr("fill", e => color(e.key))
.selectAll("rect")
.data(e => e, e => e.key)
.join("rect")
.attr("x", (e, i) => x1(e.data.year))
.attr("y", e => y1(e[1]))
.attr("height", e => y1(e[0]) - y1(e[1]))
.attr("width", x1.bandwidth())
.on("mouseover", (event, d) => {
const [xValue, yValue] = [d.data.year, d[1] - d[0]];
const category = d3.select(event.target.parentNode).datum().key;
tooltip.style("visibility", "visible")
.html(`Energy Sector: ${category}<br>Year: ${xValue}<br>Energy Generated: ${yValue} MWh`)
.style("left", `${event.pageX}px`)
.style("top", `${event.pageY}px`);

d3.select(event.target)
.style("opacity", 0.7)
.style("stroke", "black")
.style("stroke-width", "2px");
})
.on("mouseout", (event, d) => {
tooltip.style("visibility", "hidden");

d3.select(event.target)
.style("opacity", 1)
.style("stroke", "none");
});

svg.append("text")
.attr("x", width1 / 2)
.attr("y", height1 - margin.bottom / 100)
.attr("text-anchor", "middle")
.text("Year");

svg.append("text")
.attr("x", -height1 / 2)
.attr("y", margin.left / 3.5)
.attr("text-anchor", "middle")
.attr("transform", "rotate(-90)")
.text("Energy Generated MWh");

const legend = svg.selectAll(".legend")
.data([...columns, "all"])
.enter()
.append("g")
.attr("class", "legend")
.attr("transform", (d, i) => `translate(120, ${i * 20})`);

legend.append("rect")
.attr("x", width1 - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", d => (d === "all" ? "gray" : color(d)));

legend.append("text")
.attr("x", width1 - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(d => (d === "all" ? "All" : d));

svg.append("g")
.attr("transform", `translate(0,${height1 - margin.bottom})`)
.call(xAxis1)
.append("text")
.attr("x", width1 / 2)
.attr("y", margin.bottom / 2)
.attr("fill", "black")
.attr("text-anchor", "middle");

svg.append("g")
.attr("transform", `translate(${margin.left}, 0)`)
.call(yAxis1);

return svg.node();
}

Insert cell
chart2 =
html`
<div style="display: flex; justify-content: space-between;">
<div id="chart1" style="width: 45%;">
<div>${viewof chosenState}</div>
<div>${chart}</div>
</div>
<div id="chart2" style="width: 45%;">
<div>${viewof chosenState1}</div>
<div>${chart1}</div>
</div>
</div>
`


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