viewof top10byprice = {
selecteddModel;
activeModel;
const sortedData = topCompaniesFiltered
.slice()
.sort((a, b) => b.avgPrice - a.avgPrice);
const companyOrder = sortedData.map(d => d.company);
const activeCompany = activeModel?.company;
const selectedCompany = selectedModel && data.find(d => d["Model Name"] === selecteddModel)?.["Company Name"];
const chart = Plot.plot({
width: 850,
height: 600,
marginLeft: 140,
marginRight: 40,
x: {
label: "Average Launch Price (USD)",
grid: true,
tickFormat: d => `$${d.toLocaleString()}`,
domain: [0, 4100]
},
y: {
label: "Company",
domain: companyOrder
},
color: { legend: false },
marks: [
Plot.barX(
sortedData.filter(d => d.company === activeCompany && d.company === selectedCompany),
{
x: d => d.avgPrice + 100,
y: "company",
fill: "#0d9488"
}
),
// Selected only
Plot.barX(
sortedData.filter(d => d.company === selectedCompany && d.company !== activeCompany),
{
x: d => d.avgPrice + 100,
y: "company",
fill: "#1e3a8a"
}
),
// Clicked only
Plot.barX(
sortedData.filter(d => d.company === activeCompany && d.company !== selectedCompany),
{
x: d => d.avgPrice + 100,
y: "company",
fill: "#4caf50"
}
),
// Default
Plot.barX(
sortedData.filter(d => d.company !== selectedCompany && d.company !== activeCompany),
{
x: d => d.avgPrice + 100,
y: "company",
fill: "#90caf9"
}
),
Plot.ruleX([0])
]
});
// Add interactivity
chart.querySelectorAll("rect").forEach((bar, i) => {
const d = sortedData[i];
const company = d.company;
bar.style.cursor = "pointer";
let clickCount = 0;
let timer;
bar.addEventListener("click", () => {
clickCount++;
if (clickCount === 1) {
// Wait for possible double click
timer = setTimeout(() => {
// Single click
if (activeModel?.company === company) {
// Do nothing on single click if already selected
} else {
const recentModel = validData
.filter(e => e["Company Name"] === company)
.sort((a, b) => +b["Launched Year"] - +a["Launched Year"])[0];
if (recentModel) {
mutable activeModel = {
company: recentModel["Company Name"],
model: recentModel["Model Name"],
year: recentModel["Launched Year"]
};
} else {
mutable activeeModel = { company };
}
}
clickCount = 0;
}, 250);
} else {
// Double click
clearTimeout(timer);
mutable activeModel = null;
clickCount = 0;
}
});
});
return chart;
}