{
const height = 400;
const margin = 30;
const svg = d3.create('svg')
.attr('width', width)
.attr('height', height + margin*2);
const chart = svg.append('g')
.attr('transform', 'translate('+margin+','+margin+')');
const maxY = Math.round(d3.max(data, d=>d.avgPetalLen));
const yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, maxY ])
const xScale = d3.scaleBand()
.range([0, width])
.padding(.5)
.domain(data.map(d=>d.species))
chart.append('g')
.call(
d3.axisLeft(yScale)
.tickFormat(function(d){
d3.select(this)
.attr("font-weight", "bold")
.attr("font-size", "14px")
return d;
})
)
.append("text")
.attr('transform', "rotate(-90)")
.attr("y", 10)
.attr("dy", 10)
.attr("text-anchor", "end")
.attr("fill", 'black')
.attr("font-weight", "bold")
.attr("font-size", "18px")
.text("CM");
chart.append('g')
.attr('transform', 'translate(0, '+ height+')')
.call(d3.axisBottom(xScale))
.attr("font-size", 18);
const tooltip = d3.select("body").append("div")
.attr("class", "tooltip")
.attr('position', 'absolute')
.style("opacity", 0);
window.onmousemove = function (e) {
const x = (e.clientX - 25) + 'px', y = (e.clientY - 25) + 'px';
tooltip.style("left", x).style("top", y);
};
const colorScale = d3.scaleOrdinal(d3.schemeCategory10)
chart.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", d=>xScale(d.species))
.attr("y", d=>yScale(d.avgPetalLen))
.attr("width", xScale.bandwidth())
.attr("height", d=> height-yScale(d.avgPetalLen) )
.attr("fill", d=>colorScale(d))
.on("mouseover", function(event, d){
tooltip.transition()
.duration(200)
.style("opacity", 1);
tooltip.html(d3.format('.2')(d.avgPetalLen) + " CM");
})
.on("mouseout", function(event, d){
tooltip.transition()
.duration(200)
.style("opacity", 0);
});
svg.append("text")
.attr("transform", "translate(0,0)")
.attr("x", 150)
.attr("y", 50)
.attr("font-size", "24px")
.text("Iris Petal Length")
return svg.node()
}