我正在为数据写一张条形图,它显示了多个攻击战术和其他信息.战术显示在X轴上,并进行了排序.我希望当他们有多个相同的战术堆叠在一起的时候.堆叠条形图的所有其他示例都使用.STACK,我非常肯定它并不真正适用于这种情况.
<!DOCTYPE html>
<meta charset="utf-8">
<!-- Load d3.js -->
<script src="https://d3js.org/d3.v4.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
var margin = {top: 30, right: 30, bottom: 70, left: 60},
width = 1000 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
barheight = 60;
// append the svg object to the body of the page
var 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/BaileyHCUDenver/KPCUDTEST/main/test-data-short.csv", function(data) {
// X axis
var x = d3.scaleBand()
.range([ 0, width ])
.domain(data.map(function(d) { return d.tactic; }))
.padding(0.2);
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x))
.selectAll("text")
.attr("transform", "translate(-10,0)rotate(-)")
.style("text-anchor", "end");
// Add Y axis //Not needed to show the Y axis because their is no need for it
//var y = d3.scaleLinear()
//.domain([0, 20])
//.range([ height, 0]);
//svg.append("g")
//.call(d3.axisLeft(y));
// Bars
svg.selectAll("mybar")
.data(data)
.enter()
.append("rect")
.attr("x", function(d) { return x(d.tactic); })
.attr("y", function(d) {
return height - barheight;
})
.attr("width", x.bandwidth())
.attr("height", function(d) { return barheight; })
.attr("fill", "#FFFFFF") //Fill in with white
.attr("stroke", "black") // Black outline color
.attr("stroke-width", ); // Outline width (adjust as needed)
svg.selectAll("mytext")
.data(data)
.enter()
.append("text")
.text(function (d) { return d.title; }) // Use the 'value' field from your data
.attr("x", function (d) { return x(d.tactic) + x.bandwidth() / 2; }) // Center the text
.attr("y", function (d) { return height - barheight + 10; }) // Adjust the vertical position
.style("text-anchor", "middle") // Center-align the text
.style("font-size", "9px") // Set font size
.style("fill", "black"); // Set text color
svg.selectAll("mytext")
.data(data)
.enter()
.append("text")
.text(function (d) { return d.tactic; }) // Use the 'value' field from your data
.attr("x", function (d) { return x(d.tactic) + x.bandwidth() / 2; }) // Center the text
.attr("y", function (d) { return height - barheight + 20; }) // Adjust the vertical position
.style("text-anchor", "middle") // Center-align the text
.style("font-size", "9px") // Set font size
.style("fill", "black"); // Set text color
})
</script>
任何帮助都将不胜感激,因为我不确定如何才能让这些盒子堆叠在一起