猿问

为什么条形会出现“倒数值”?d3.js

我正在尝试学习如何在 React 中使用 d3.js,但我的代码有问题。

我正在做一个条形图,但是条形的值是“倒置的”,例如,条形的值为 30%,但在图表中,条形显示为 70%(例如,100% - 30% = 70 %)。 我该如何解决?

这是我的代码:codeSandBox。

我的另一个问题是:如何更改条形的高度?我想添加一些 margin-top 来显示 y 轴的所有内容,但是如果我这样做,条形仍然具有相同的高度并且与 yAxis 值不匹配


函数式编程
浏览 119回答 2
2回答

哆啦的时光机

这里的问题是您正在交换y和height逻辑,它应该是:.attr("y", d => yScale(d.percent)).attr("height", d => height - margin.bottom - margin.top - yScale(d.percent))&nbsp;或者,如果您将工作高度设置为...height = totalHeight - margin.bottom - margin.top...它可以只是:.attr("y", d => yScale(d.percent)).attr("height", d => height - yScale(d.percent))&nbsp;最重要的是(这解决了您的第二个问题),您错误地使用了 Bostock 的保证金约定。您应该g根据边距翻译该组,然后将所有小节附加到该已翻译组中,而无需再次翻译它们。此外,将轴的组附加到该g组。话虽如此,这是具有这些更改的代码:const data = [{&nbsp; &nbsp; year: 2012,&nbsp; &nbsp; percent: 50&nbsp; },&nbsp; {&nbsp; &nbsp; year: 2013,&nbsp; &nbsp; percent: 30&nbsp; },&nbsp; {&nbsp; &nbsp; year: 2014,&nbsp; &nbsp; percent: 90&nbsp; },&nbsp; {&nbsp; &nbsp; year: 2015,&nbsp; &nbsp; percent: 60&nbsp; },&nbsp; {&nbsp; &nbsp; year: 2016,&nbsp; &nbsp; percent: 75&nbsp; },&nbsp; {&nbsp; &nbsp; year: 2017,&nbsp; &nbsp; percent: 20&nbsp; }];const height = 300;const width = 370;const margin = {&nbsp; top: 20,&nbsp; right: 10,&nbsp; bottom: 20,&nbsp; left: 25};const xScale = d3.scaleBand()&nbsp; .domain(data.map(d => d.year))&nbsp; .padding(0.2)&nbsp; .range([0, width - margin.right - margin.left]);const yScale = d3&nbsp; .scaleLinear()&nbsp; .domain([0, 100])&nbsp; .range([height - margin.bottom - margin.top, 0]);const svg = d3&nbsp; .select("body")&nbsp; .append("svg")&nbsp; .attr("width", width)&nbsp; .attr("height", height)&nbsp; .style("margin-left", 10);const g = svg&nbsp; .append("g")&nbsp; .attr("transform", `translate(${margin.left}, ${margin.top})`);g&nbsp; .selectAll("rect")&nbsp; .data(data)&nbsp; .enter()&nbsp; .append("rect")&nbsp; .attr("x", d => xScale(d.year))&nbsp; .attr("y", d => yScale(d.percent))&nbsp; .attr("width", xScale.bandwidth())&nbsp; .attr("height", d => height - margin.bottom - margin.top - yScale(d.percent))&nbsp; .attr("fill", "steelblue")g.append("g")&nbsp; .call(d3.axisLeft(yScale));g.append("g")&nbsp; .call(d3.axisBottom(xScale))&nbsp; .attr(&nbsp; &nbsp; "transform",&nbsp; &nbsp; `translate(0, ${height - margin.bottom - margin.top})`&nbsp; );<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

蓝山帝景

svg&nbsp; &nbsp; &nbsp; .selectAll("rect")&nbsp; &nbsp; &nbsp; .data(data)&nbsp; &nbsp; &nbsp; .enter()&nbsp; &nbsp; &nbsp; .append("rect")&nbsp; &nbsp; &nbsp; .attr("x", d => xScale(d.year))&nbsp; &nbsp; &nbsp; .attr("y", d => height - yScale(100-d.percent))&nbsp; &nbsp; &nbsp; .attr("width", xScale.bandwidth())&nbsp; &nbsp; &nbsp; .attr("height", d => yScale(100-d.percent))&nbsp; &nbsp; &nbsp; .attr("fill", "steelblue")&nbsp; &nbsp; &nbsp; .attr("transform", `translate(${margin.left}, -${margin.bottom})`);你需要减去 100 的百分比工作:https : //codesandbox.io/s/crimson-microservice-8kjqd
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答