gpt4 book ai didi

javascript - d3 path.line stroke-width with IF 语句/三元运算符

转载 作者:行者123 更新时间:2023-11-30 20:02:24 24 4
gpt4 key购买 nike

尝试使用 IF 语句/三元运算符更改线条笔画宽度,例如if d.country === "China"stroke-width: 2。这必须是一个 path.line 属性,所以这就是我在调用 line 之后附加的内容。

我已将 countryName 添加到 emissions 对象,我还注意到条件始终为 FALSE,因此 stroke-width 为 0.5。为什么它不是真的?

Codepen

//Define line chart with and height 
const width = fullWidth - margin.left - margin.right;
const height = fullHeight - margin.top - margin.bottom;

//Define x and y scale range
let xScale = d3.scaleLinear()
.range([0, width])

let yScale = d3.scaleLinear()
.range([0, height])

//Define x and y axis
let xAxis = d3.axisBottom(xScale)
.ticks(15)

let yAxis = d3.axisLeft(yScale)
.ticks(10)


//Draw svg
let svg = d3.select("body")
.append("svg")
.attr("width", fullWidth)
.attr("height", fullHeight)
.append("g")
.attr("transform", "translate(" + 53 + "," + 0 +")");

d3.json("https://api.myjson.com/bins/izmg6").then(data => {
console.log(data);



//Structure data so should be an array of arrays etc [[x,y], [x,y], [x,y]]

let years = d3.keys(data[0]).slice(0, 50);
console.log(years);

let dataset = [];

data.forEach((d, i) => {

let myEmissions = [];

years.forEach(y => {
if (d[y]) {

myEmissions.push({
country: d.countryName,
year: y,
amount: d[y]
})
}
})

dataset.push({
country: d.countryName,
emissions: myEmissions
});
})

console.log(dataset);

//Define x and y domain
xScale
.domain(d3.extent(years, d =>d))

yScale
.domain([d3.max(dataset, d =>
d3.max(d.emissions, d =>
+d.amount)), 0])


//Generate line
let line = d3.line()
.curve(d3.curveBasis)
.x(d =>
xScale(d.year))
.y(d =>
yScale(d.amount));


let groups = svg.selectAll("g")
.data(dataset)
.enter()
.append("g")


groups.append("title")
.text(d => d.country)


groups.selectAll("path")
.data(d => [d.emissions])
.enter()
.append("path").classed("line", true)
.attr("d", line)
.style("stroke-width", d =>
d.country === "China" ? 10 : 0.5
)


}).catch(error => console.log(error))

最佳答案

rioV8 的意思是你已经有了你的组选择,所以你只需要使用 groups 来追加新元素。

groups 是所有 g 的选择,它是您要附加路径的地方。与您不再选择添加标题的方式相同。

groups
.append("path").classed("line", true)
.attr("d", d=> line(d.emissions))
.style("stroke-width", d =>
d.country === "China" ? 5 : 0.5
)

关于javascript - d3 path.line stroke-width with IF 语句/三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53240908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com