d3使用功能更改轴上刻度的颜色

  • 本文关键字:颜色 功能 d3 d3.js
  • 更新时间 :
  • 英文 :


我在d3中有一个x轴,每个刻度都有标签和圆圈。我想用一个函数改变每个点的颜色,这样颜色就来自一个数组。

我已经有了一个函数,可以从数组中获取记号并将其定位在刻度上,但同样的逻辑不适用于更改每个圆的属性。

我希望能够选择每一个圆圈,它是.tick类的子类,并更改它的笔划属性:

svg.selectAll(".tick", "circle")
.each(d => {
var dot = d3.select(d, "circle").attr("stroke", "red")
console.log("DOT", dot)
return dot
})

我可能会将each更改为一个合适的for循环,通过匹配索引来迭代数据和圆数组。

如何使圆的颜色与数组"数据"中对象的颜色相对应?

import React, {useState, useEffect} from 'react';
import * as d3 from 'd3';
import './App.css';
function App() {
const [currentYear, setCurrentYear] = useState(2020);
const [maxYear, setMaxYear] = useState(30);
const [data, setData] = useState(
[
{x: 2020, colour: "purple", y1: 0.001, y2: 0.63},
{x: 2027, colour: "red", y1: 0.003, y2: 0.84},
{x: 2031, colour: "yellow", y1: 0.024, y2: 0.56},
{x: 2035, colour: "green", y1: 0.054, y2: 0.22},
{x: 2040, colour: "blue", y1: 0.062, y2: 0.15},
{x: 2050, colour: "orange", y1: 0.062, y2: 0.15}
]
);
const initialiseData = () => {
const svg = d3.select( "svg" );
const pxX = svg.attr( "width" );
const pxY = svg.attr( "height" );
const makeScale = ( accessor, range ) => {
console.log("RANGE", accessor, range)
return d3.scaleLinear()
.domain( d3.extent( data, accessor ) )
.range( range )
.nice()
}
const scX = makeScale( d => d["x"], [0, pxX - 50]);
const g = d3.axisBottom( scX ).tickValues(
data.map(d => {
return d.x 
})
)

svg.append( "g" )
.attr( "transform", "translate(" + 25 + "," + pxY/2 + ")")
.call( g );
svg.selectAll(".domain").attr( "visibility", "hidden" );
svg.selectAll( ".tick" )
.append("circle")
.attr("cx", 0)
.attr("cy", 0)
.attr("r", 5)
.attr("fill", "white")
.attr("stroke", "grey")
.attr("stroke-width", "4px")
svg.selectAll(".tick line")
.attr("visibility", "hidden")

svg.selectAll( ".tick text")
.attr("font-size", 20)
.attr("dy", "1.5em")
svg.selectAll(".tick", "circle")
.each(d => {
var dot = d3.select(d, "circle")
console.log("DOT", dot)
return 
})
}

useEffect(() => {
if (data) {
initialiseData();
}
}, [data])
return (
<div className="App">
<svg id="demo1" width="1200" height="400" style={{background: "lightgrey"}}/>
</div>
);
}
export default App;

您的svg.selectAll( ".tick" ).append("circle")创建圆。使用selectAll有点像执行for循环:它创建了许多元素,每次数据都被绑定到创建的元素

您可以为.attr()(以及D3中的大多数其他内容(提供一个函数,该函数将绑定数据作为参数,通常编写为d。如果放入selectAll,它将应用于每个元素。

请参阅学习D3:连接以获得更完整的解释。综合起来:

svg.selectAll( ".tick" )
.data(data)
.append("circle")
.attr("fill", d => d.colour) // d is an element of the data: get colour from it

最新更新