1 graph per item in d3js

This commit is contained in:
Sam Hadow 2024-01-14 01:01:42 +01:00
parent c6a18d84b0
commit 96c529c6f3

View File

@ -4,13 +4,17 @@
<!-- Load d3.js --> <!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script> <script src="https://d3js.org/d3.v6.js"></script>
<!-- Create a div where the graph will take place --> <!-- Create a div where the graphs will take place -->
<div id="my_dataviz"></div> <div id="graphs"></div>
<script> <script>
// set the dimensions and margins of the graph // set the dimensions and margins of the graph
const margin = {top: 10, right: 30, bottom: 30, left: 60}, const margin = {
top: 10,
right: 30,
bottom: 30,
left: 60
},
width = 1600 - margin.left - margin.right, width = 1600 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom; height = 400 - margin.top - margin.bottom;
@ -20,87 +24,109 @@ const svg = d3.select("#my_dataviz")
.attr("width", width + margin.left + margin.right) .attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom) .attr("height", height + margin.top + margin.bottom)
.append("g") .append("g")
.attr("transform",`translate(${margin.left},${margin.top})`); .attr("transform", `translate(${margin.left},${margin.top})`);
d3.csv('http://127.0.0.1/output.csv', d => { d3.csv('http://127.0.0.1/output.csv', d => {
console.log(d.h_timestamp);
console.log(d3.timeParse("%Y-%m-%d %H:%M:%S.%L")(d.h_timestamp));
//2024-01-13 21:51:45.581863
return { return {
date: new Date(d.h_timestamp.replace(' ', 'T')).getTime(), date: new Date(d.h_timestamp.replace(' ', 'T')).getTime(),
value: parseFloat(d.price.replace('$', '')) value: parseFloat(d.price.replace('$', '')),
skuid: d.skuid
} }
}).then(function(data) { }).then(function(data) {
console.log(data);
// Add X axis --> it is a date format
const x = d3.scaleTime() const x = d3.scaleTime()
.domain(d3.extent(data, d => d.date)) .domain(d3.extent(data, d => d.date))
.range([ 0, width ]); .range([0, width]);
svg.append("g")
// Group the data by (itemid, skuid)
const nestedData = d3.group(data, d => d.skuid);
// Create a div for each graph
const graphDivs = d3.select("#graphs")
.selectAll(".graph-container")
.data(nestedData.keys())
.enter().append("div")
.attr("class", "graph-container");
// Append SVG elements to each div
const svgs = graphDivs.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
var dict_xAxis = {};
// Plot each curve
svgs.each(function(key) {
const dataSubset = nestedData.get(key);
const y = d3.scaleLinear()
.domain([d3.min(dataSubset, d => d.value) - 1, d3.max(dataSubset, d => d.value) + 1])
.range([height, 0]);
const svg = d3.select(this);
dict_xAxis[dataSubset] = svg.append("g")
.attr("transform", `translate(0, ${height})`) .attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x)); .call(d3.axisBottom(x));
// Add Y axis
// Get the extent of the data values
const valueExtent = d3.extent(data, d => d.value);
// Extend the domain by 5 units on each side
const extendedDomain = [valueExtent[0] - 5, valueExtent[1] + 5];
// Create the y-scale with the extended domain
const y = d3.scaleLinear()
.domain(extendedDomain)
.range([height, 0]);
svg.append("g") svg.append("g")
.call(d3.axisLeft(y)); .call(d3.axisLeft(y));
// Add the line
svg.append("path") svg.append("path")
.datum(data) .datum(dataSubset)
.attr("fill", "none") .attr("fill", "none")
.attr("stroke", "black") .attr("stroke", "black")
.attr("stroke-width", 1.5) .attr("stroke-width", 1.5)
.attr("d", d3.line() .attr("d", d3.line()
.curve(d3.curveBasis) // Just add that to have a curve instead of segments
.x(d => x(d.date)) .x(d => x(d.date))
.y(d => y(d.value)) .y(d => y(d.value))
) );
// create a tooltip // Add the points
const Tooltip = d3.select("#my_dataviz") svg
.append("div") .append("g")
.selectAll("dot")
.data(dataSubset)
.join("circle")
.attr("class", "myCircle")
.attr("cx", d => x(d.date))
.attr("cy", d => y(d.value))
.attr("r", 8)
.attr("stroke", "#69b3a2")
.attr("stroke-width", 3)
.attr("fill", "white");
// interaction
// Create a tooltip for each graph
const Tooltip = d3.select("body").append("div")
.style("opacity", 0) .style("opacity", 0)
.attr("class", "tooltip") .attr("class", "tooltip")
.style("background-color", "white") .style("background-color", "white")
.style("border", "solid") .style("border", "solid")
.style("border-width", "2px") .style("border-width", "2px")
.style("border-radius", "5px") .style("border-radius", "5px")
.style("padding", "5px") .style("padding", "5px");
// Three function that change the tooltip when user hover / move / leave a cell // Interaction functions for each graph
const mouseover = function(event,d) { const mouseover = function(event, d) {
Tooltip Tooltip.style("opacity", 1);
.style("opacity", 1) };
}
const mousemove = function(event,d) { const mousemove = function(event, d) {
Tooltip Tooltip
.html("Exact value: " + d.value) .html("Exact value: " + d.value)
.style("left", `${event.layerX+10}px`) .style("left", `${event.pageX + 10}px`)
.style("top", `${event.layerY}px`) .style("top", `${event.pageY}px`);
} };
const mouseleave = function(event,d) {
Tooltip
.style("opacity", 0)
}
const mouseleave = function(event, d) {
Tooltip.style("opacity", 0);
};
// Add interaction to the points for each graph
// Add the points svg.append("g")
svg
.append("g")
.selectAll("dot") .selectAll("dot")
.data(data) .data(dataSubset)
.join("circle") .join("circle")
.attr("class", "myCircle") .attr("class", "myCircle")
.attr("cx", d => x(d.date)) .attr("cx", d => x(d.date))
@ -111,6 +137,124 @@ d3.csv('http://127.0.0.1/output.csv', d => {
.attr("fill", "white") .attr("fill", "white")
.on("mouseover", mouseover) .on("mouseover", mouseover)
.on("mousemove", mousemove) .on("mousemove", mousemove)
.on("mouseleave", mouseleave) .on("mouseleave", mouseleave);
// // zoom
// // Add a clipPath for each graph
// var clip = svg.append("defs").append("svg:clipPath")
// .attr("id", "clip-" + key)
// .append("svg:rect")
// .attr("width", width)
// .attr("height", height)
// .attr("x", 0)
// .attr("y", 0);
//
// // Create zoom behavior for each graph
// var zoom = d3.zoom()
// .scaleExtent([1, Infinity])
// .translateExtent([
// [0, 0],
// [width, height]
// ])
// .extent([
// [0, 0],
// [width, height]
// ])
// .on("zoom", updateChart);
//
// // Add the line variable: where both the line and the brush take place
// var line = svg.append('g')
// .attr("clip-path", "url(#clip-" + key + ")")
// .call(zoom);
//
// // Create a brush for each graph
// var brush = d3.brushX()
// .extent([
// [0, 0],
// [width, height]
// ])
// .on("end", updateChart);
//
// // Add the line
// line.append("path")
// .datum(dataSubset)
// .attr("class", "line") // I add the class line to be able to modify this line later on.
// .attr("fill", "none")
// .attr("stroke", "steelblue")
// .attr("stroke-width", 1.5)
// .attr("d", d3.line()
// .x(function(d) {
// return x(d.date)
// })
// .y(function(d) {
// return y(d.value)
// })
// );
//
// // Add the brushing
// line.append("g")
// .attr("class", "brush")
// .call(brush);
//
// // A function that set idleTimeOut to null
// let idleTimeout
//
// function idled() {
// idleTimeout = null;
// }
//
// // A function that update the chart for given boundaries
// function updateChart(event, d) {
// // What are the selected boundaries?
// var extent = event.selection
//
// // If no selection, back to initial coordinate. Otherwise, update X axis domain
// if (!extent) {
// x.domain([4, 8]);
// } else {
// x.domain([x.invert(extent[0]), x.invert(extent[1])]);
// line.select(".brush").call(brush.move, null); // This removes the grey brush area as soon as the selection has been done
// }
//
// // Update axis and line position
// dict_xAxis[dataSubset].transition().duration(1000).call(d3.axisBottom(x));
// line
// .select('.line')
// .transition()
// .duration(1000)
// .attr("d", d3.line()
// .x(function(d) {
// return x(d.date)
// })
// .y(function(d) {
// return y(d.value)
// })
// );
// }
//
// // If user double click, reinitialize the chart
// svg.on("dblclick", function() {
// x.domain(d3.extent(data, function(d) {
// return d.date;
// }))
// dict_xAxis[dataSubset].transition().call(d3.axisBottom(x));
// line
// .select('.line')
// .transition()
// .attr("d", d3.line()
// .x(function(d) {
// return x(d.date)
// })
// .y(function(d) {
// return y(d.value)
// })
// );
// });
//
//
});
}) })
</script> </script>