After creating a horizontal bar graph, I encountered several issues that need to be addressed:
- I could not hide the labels associated with the X major axis.
- I need to create dotted lines for values at 80% and 100%.
- I want rounded edges on the bar graph.
- Add a legend to the bar graph.
Below is the current code in use:
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v6.js"></script>
<!-- Create a div where the graph will take place -->
<div id="my_dataviz"></div>
<script>
// set the dimensions and margins of the graph
const margin = {top: 20, right: 30, bottom: 40, left: 90},
width = 460 - margin.left - margin.right,
height = 400 - margin.top - margin.bottom;
// append the svg object to the body page
const svg = d3.select("#my_dataviz")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", `translate(${margin.left}, ${margin.top})`);
// Parse the Data
d3.csv("https://raw.githubusercontent.com/holtzy/data_to_viz/master/Example_dataset/7_OneCatOneNum_header.csv").then( function(data) {
// Add X axis
const x = d3.scaleLinear()
.domain([0, 1000])
.range([ 0, width]);
svg.append("g")
.attr("transform", `translate(0, ${height})`)
.call(d3.axisBottom(x).tickSize(0))
.select(".domain").remove();
// Y axis
const y = d3.scaleBand()
.range([ 0, height ])
.domain(data.map(d => d.Country))
.padding(.1);
svg.append("g")
.call(d3.axisLeft(y).tickSize(0));
//Bars
svg.selectAll("myRect")
.data(data)
.join("rect")
.attr("x", x(0) )
.attr("y", d => y(d.Country))
.attr("width", d => x(d.Value))
.attr("height", y.bandwidth())
.attr("fill", "#69b3a2");
})
</script>
Current Output:
https://i.sstatic.net/2w2AR.png https://i.sstatic.net/rJPq5.pngEdit 1:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
...
Current Output After Edit 1:
https://i.sstatic.net/08ejP.pngEdit 2: Problems that still remains
- Grid lines
- Legends
Updated Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
...
Edit 2 Output:
https://i.sstatic.net/z3SsZ.pngEdit code suggested by Omar:
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<!DOCTYPE html>
<meta charset="utf-8">
...
Current Output:
https://i.sstatic.net/hQTif.png For any help, I would greatly appreciate it. Thank you in advance!