Public
Edited
Apr 6, 2023
Insert cell
Insert cell
function createLinePlot1(
featureMaps,
featureMapKey,
originalData,
height = 300
) {
const { plotData, histogramData } = preprocess1DData2(
featureMaps,
featureMapKey,
originalData
);
const featureName = featureMaps["1D"][featureMapKey].feature;

const xValues = data.map((d) => d.x);
const minXValue = Math.min(...xValues);
const maxXValue = Math.max(...xValues);
console.log("asdasd", minXValue, maxXValue);

const linePlot = vl
.markLine() // Make a line chart
.data(plotData) // Using the provided data
.encode(
vl.x().fieldQ("x").title(featureName), // For x, use the x field and set the title
vl.y().fieldQ("y"), // For y, use the y field
vl.tooltip().fieldN("class") // For tooltips, show the class field
);

console.log(histogramData);

const numBins = 20;

// Calculate the bin size
const binSize = (maxXValue - minXValue) / numBins;
console.log("binSize", binSize);

// Create an array of bin edges
const binEdges = Array.from(
{ length: numBins + 1 },
(_, i) => minXValue + i * binSize
);

console.log("binEdges", binEdges);

// Create two arrays of objects representing the bins for each class
const bins0 = binEdges.slice(0, -1).map((binStart, i) => ({
binStart,
binEnd: binEdges[i + 1],
count: 0
}));
const bins1 = binEdges.slice(0, -1).map((binStart, i) => ({
binStart,
binEnd: binEdges[i + 1],
count: 0
}));

// Iterate over the data and increment the count for the appropriate bin and class
originalData.forEach((d) => {
const binIndex = Math.floor((d.x - minXValue) / binSize);
if (binIndex >= 0 && binIndex < numBins) {
if (d.target === 0) {
bins0[binIndex].count += 1;
} else {
bins1[binIndex].count += 1;
}
}
});

// Combine the two arrays of bins into a single array
const combinedBins = [...bins0, ...bins1].map((bin, i) => ({
...bin,
class: i < numBins ? "Class_0" : "Class_1"
}));

console.log("histogramData", histogramData);

// Create a Vega-Lite specification using the manually calculated bins
const histogram = vl
.markBar()
.data(combinedBins)
.encode(
vl.y().value(0),
vl.y2().value(height),
vl
.x()
.fieldQ("binStart")
.scale({ domain: [minXValue, maxXValue] }),
vl.x2().fieldQ("binEnd"),
vl
.opacity()
.fieldQ("count")
.scale({ domain: [0, 1], range: [0, 0.02] }),
vl.color().fieldN("class")
);
const zeroLine = vl
.markRule({ strokeDash: [5, 5] }) // Make a dashed line
.data([{ y: 0 }]) // At y=0
.encode(vl.y().fieldQ("y"));

return vl.layer(histogram, linePlot, zeroLine).height(height).render(); // Combine the charts using layer
}
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