Drawing a Horizontal Bar Graph with D3.js
Drawing a Horizontal Bar Graph
View code
Explanation
// Data set
const dataSet = [100, 200, 20, 45, 300];
// Draw the graph
drawGraph(dataSet);
function drawGraph(dataSet) {
const maxValue = Math.max(...dataSet);
const OriginAttr = {
fill: "rgba(255, 0, 0, 0)"
};
d3.select("#graphArea")
.selectAll("rect") // Set the target elements
.data(dataSet) // Set the data set
.enter() // Add elements based on the number of data items
.append("rect") // Create SVG rectangles
.attr("x", 0) // X coordinate (starting point)
.attr("y", (d, i) => {
return i * 25;
}) // Y coordinate (drawing position for each data item)
.attr("width", (d, i) => {
return `${d}px`;
}) // Width of the horizontal bar graph (end point on the X axis)
.attr("height", "20px") // Height of the horizontal bar graph
.attr("fill", (d, i) => {
return `rgba(255, 0, 0, ${d / maxValue})`;
}) // Bar graph color
.on("mouseover", function () {
OriginAttr.fill = this.attributes.fill.value; // Remember the previous state
d3.select(this)
.attr("fill", "blue"); // Change the color of the selected graph
})
.on("mouseout", function () {
d3.select(this)
.attr("fill", OriginAttr.fill); // Restore the previous state
});
}