[英]How do I set the X values for a singled stacked horizontal bar chart using d3.js?
I am trying to set the x attribute values of single stacked horizontal bar chart.我正在尝试设置单个堆叠水平条形图的 x 属性值。 After messing with javascript for about an hour, I can't seem to get the x values lined up so that the bars line up one after the other from largest value to smallest.
在弄乱了 javascript 大约一个小时后,我似乎无法将 x 值排成一行,以便条形从最大值到最小值一个接一个地排列。
Below is my js:下面是我的js:
const abuseNeglectData = [
{
type: "Neglected-Related",
data: 122214,
color: "red",
},
{
type: "Abuse-Related",
data: 47364,
color: "orange",
},
{
type: "Other",
data: 2972,
color: "blue",
},
];
dataSum = d3.sum(abuseNeglectData, d=>{return d.data})
const width = 400,
height = 100,
bottom = 20,
xScale = d3
.scaleLinear()
.range([0,width])
.domain([
0,dataSum
]),
xBand = d3.scaleBand()
.range([0,width])
.domain(abuseNeglectData.map(d=>{return d.data}));
const svg = d3.select('.graph-wrapper.abuse-neglect').append('svg')
.attr('width', width)
.attr('height', height + bottom);
svg.append('g').attr('class','bars').selectAll('rect')
.data(abuseNeglectData)
.enter()
.append('rect')
.attr('y', d=>{return 0})
.attr('height',d=>{return height})
.style('width',d=> {return xScale(d.data)+'px'})
.style('fill', d=>{return d.color})
.attr('x',d=>{return xBand(d.data)})
//xaxis
svg.append('g').attr('class','x-axis')
.call(d3.axisBottom(xBand))
.attr('transform',`translate(0,${height})`)
Thanks for the help.谢谢您的帮助。
You can manually calculate the x coordinate for each bar based on the preceding elements' values, which offsets the rect.您可以根据前面元素的值手动计算每个条的 x 坐标,这会偏移矩形。 The example below does that within a forEach loop.
下面的示例在 forEach 循环中执行此操作。
const abuseNeglectData = [ { type: "Neglected-Related", data: 122214, color: "red", }, { type: "Abuse-Related", data: 47364, color: "orange", }, { type: "Other", data: 2972, color: "blue", }, ]; dataSum = d3.sum(abuseNeglectData, d=>{return d.data}) let offset = 0 abuseNeglectData.forEach(function(d){ d.offset = offset offset = offset + d.data }) const width = 400, height = 100, bottom = 20, xScale = d3.scaleLinear().range([0,width]).domain([ 0,dataSum ]); const svg = d3.select('body'/*'.graph-wrapper.abuse-neglect'*/).append('svg').attr('width', width).attr('height', height + bottom); svg.append('g').attr('class','bars').selectAll('rect').data(abuseNeglectData).enter().append('rect').attr('y', d=>{return 0}).attr('height',d=>{return height}).style('width',d=> {return xScale(d.data)+'px'}).style('fill', d=>{return d.color}).attr('x',d=>{return xScale(d.offset)}) svg.append('g').attr('class','x-axis').call(d3.axisBottom(xScale)).attr('transform',`translate(0,${height})`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.