chart4 = {
spotify_data.forEach(d => {
d.track_popularity = +d.track_popularity;
});
const genreAvgPopularity = d3.rollup(
spotify_data,
v => d3.mean(v, d => d.track_popularity),
d => d.playlist_genre
);
const genreData = Array.from(genreAvgPopularity, ([genre, avgPopularity]) => ({
genre,
avgPopularity
}));
genreData.sort((a, b) => b.avgPopularity - a.avgPopularity);
const width = 640;
const height = 400;
const marginTop = 25;
const marginRight = 20;
const marginBottom = 35;
const marginLeft = 40;
const x = d3.scaleBand()
.domain(genreData.map(d => d.genre))
.range([marginLeft, width - marginRight])
.padding(0.1);
const y = d3.scaleLinear()
.domain([0, d3.max(genreData, d => d.avgPopularity)])
.nice()
.range([height - marginBottom, marginTop]);
const color = d3.scaleOrdinal()
.domain(genreData.map(d => d.genre))
.range([
"#D84B9B",
"#C54B9B",
"#6A0DAD",
"#8A2BE2",
"#D5A6D2",
"#9B30FF",
"#E9A3D1",
"#C71585",
"#DA70D6"
]);
const svg = d3.create("svg")
.attr("width", width)
.attr("height", height)
.attr("viewBox", [0, 0, width, height])
.attr("style", "max-width: 100%; height: auto;");
svg.append("text")
.attr("x", width / 2)
.attr("y", marginTop - 10)
.attr("text-anchor", "middle")
.attr("font-size", "16px")
.attr("font-weight", "bold")
.text("Average Track Popularity by Genre");
svg.append("g")
.attr("transform", `translate(0,${height - marginBottom})`)
.call(d3.axisBottom(x))
.selectAll("text")
.style("text-anchor", "middle")
.style("font-size", "10px")
.attr("dx", "-.8em")
.attr("dy", ".15em");
svg.append("g")
.attr("transform", `translate(${marginLeft},0)`)
.call(d3.axisLeft(y));
svg.append("g")
.selectAll("rect")
.data(genreData)
.join("rect")
.attr("x", d => x(d.genre))
.attr("y", d => y(d.avgPopularity))
.attr("width", x.bandwidth())
.attr("height", d => height - marginBottom - y(d.avgPopularity))
.attr("fill", (d, i) => color(i));
svg.append("text")
.attr("x", width / 2)
.attr("y", height - 5)
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text("Playlist Genre");
svg.append("text")
.attr("x", -height / 2)
.attr("y", 8)
.attr("transform", "rotate(-90)")
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.text("Average Track Popularity");
return svg.node();
}