【发布时间】:2022-10-23 20:43:15
【问题描述】:
我正在尝试使用从互联网上获得的一些数据创建一个简单的条形图。数据包括 300 人,其中 260 人没有有线电视订阅,其中 40 人有。这导致 13% 有订阅,87% 没有。我已经设置了 yscale 来接受这些值,一切似乎都很好,尽管由于某种原因,我的订阅栏是 87% 而我未订阅的栏是 13% 我试图找到我的代码中的缺陷,但我还没有遇到它.有谁知道为什么我的值在渲染时会被交换?
const rowConverter = (row) => {
row = {
age: parseInt(row.age),
gender: row.gender,
income: parseInt(row.income),
kids: parseInt(row.kids),
ownHome: row.ownHome === "true",
subscribed: row.subscribed === "true",
segment: row.segment
}
return { ...row };
};
const dataset = await d3.csv("./data/CableTVSubscribersData.csv", rowConverter);
const margin = {
top: 40,
bottom: 40,
left: 60,
right: 20
};
const width = 800 - margin.left - margin.right;
const height = 600 - margin.top - margin.bottom;
let subscribedCounter = 0;
let notSubscribedCounter = 0;
dataset.forEach(data => {
if (data.subscribed) {
subscribedCounter++
}
else {
notSubscribedCounter++;
}
});
let barChartRows = [
{
name: "Subscribed",
amount: subscribedCounter
},
{
name: "Not Subscribed",
amount: notSubscribedCounter
},
];
const dataset2 = barChartRows;
const barNames = dataset2.map((d) => d.name)
const svg = d3.select(".graph1")
.append("svg")
.attr("width", width + margin.left)
.attr("height", height + margin.top + margin.bottom)
.append("g")
svg.append('rect')
.attr("width", width + margin.left)
.attr("height", height + margin.top + margin.bottom)
.style("fill", "#e6e6e6");
let xScale2 = d3.scaleBand()
.domain(barNames)
.rangeRound([0, width- margin.left ]);
let yScale2 = d3.scaleLinear()
.domain([0, 1])
.rangeRound([height - margin.top, 0]);
let xAxis2 = d3.axisBottom(xScale2);
let yAxis2 = d3.axisLeft(yScale2);
let xAxisGroup = svg.append('g')
.attr('class', 'groupAxis')
.attr('transform', `translate(${margin.left + margin.right}, ${height})`)
.call(xAxis2);
let yAxisGroup = svg.append('g')
.attr('class', 'incomeAxis')
.attr('transform', `translate(${margin.left + margin.right},${margin.top})`)
.call(yAxis2)
.selectAll("text")
.text(function (d) { return d3.format(".0%")(d) });
console.log(dataset2);
svg.selectAll('.bar')
.data(dataset2)
.join(
enter => enter
.append('rect')
.attr("class",(d) => d.name)
.attr('x',(d) => xScale2(d.name)+(margin.left + margin.right)*2+10})
.attr('y',(d) => height - yScale2(d.amount/300))
.attr('width',150)
.attr('height',(d) => yScale2(d.amount/300)})
)
【问题讨论】:
-
欢迎来到 Stackoverflow。请添加一个最小的可重现示例。这会让其他人更容易帮助你。 stackoverflow.com/help/minimal-reproducible-example
标签: d3.js