如何使用d3.js按“thrid”值过滤条形图

bybem2ql  于 2022-11-12  发布在  其他
关注(0)|答案(1)|浏览(152)

我可以使用D3.js version 7绘制一个非常简单的条形图,它将名称与数据集中的点关联起来。在同一个数据集中,我想使用第三个值来过滤条形图。
我可以通过namepoints进行过滤,只需使用:

.filter((d) => d.name = "OneA")
.filter((d) => d.points > 100000)

但是如果我尝试按状态过滤条形图数据,它就不起作用了。什么都没有过滤。
下面是完整的代码:

// set margins, width and height
const MARGIN = { LEFT: 64, RIGHT: 2, TOP: 32, BOTTOM: 16 }
const WIDTH = 600 - MARGIN.LEFT - MARGIN.RIGHT
const HEIGHT = 400 - MARGIN.TOP - MARGIN.BOTTOM

// set svg
const svg = d3.select("#chart-area").append("svg")
  .attr("width", WIDTH + MARGIN.LEFT + MARGIN.RIGHT)
  .attr("height", HEIGHT + MARGIN.TOP + MARGIN.BOTTOM)

// set group
const g = svg.append("g")
  .attr("transform", `translate(${MARGIN.LEFT}, ${MARGIN.TOP})`)

// import data
d3.json("data/data.json").then(data => {
  // prepare data
  data
    .forEach(d => {
      d.points = Number(d.points)
    })

  // set scale, domain and range for x axis
  const x = d3.scaleBand()
    .domain(data.map(d => d.name))
    .range([0, WIDTH])
    .padding(0.1)
  
  // set scale, domain and range for y axis
  const y = d3.scaleLinear()
    .domain([0, d3.max(data, d => d.points)])
    .range([HEIGHT, 0])

  // call x axis
  const xAxisCall = d3.axisBottom(x)
  g.append("g")
    .attr("class", "x axis")
    .attr("transform", `translate(0, ${HEIGHT})`)
    .call(xAxisCall)

  // call y axis
  const yAxisCall = d3.axisLeft(y)
  g.append("g")
    .attr("class", "y axis")
    .call(yAxisCall)

  // join data
  const rects = g.selectAll("rect")
    .data(data)

  // enter elements to plot chart
  rects.enter().append("rect")
    .filter((d) => d.status = "ON") // THIS IS NOT WORKING. WHY?
    .attr("x", (d) => x(d.name))
    .attr("y", d => y(d.points))
    .attr("width", x.bandwidth)
    .attr("height", d => HEIGHT - y(d.points))
    .attr("fill", "steelblue")
})

而json文件中带有的数据是:

[
    {
        "name": "OneA",
        "points": "492799",
        "status": "ON"
    },
    {
        "name": "TwoB",
        "points": "313420",
        "status": "ON"
    },
    {
        "name": "ThreeC",
        "points": "133443",
        "status": "ON"
    },
    {
        "name": "FourD",
        "points": "50963",
        "status": "OFF"
    },
    {
        "name": "FiveE",
        "points": "26797",
        "status": "OFF"
    },
    {
        "name": "SixF",
        "points": "13483",
        "status": "OFF"
    },
    {
        "name": "SevenG",
        "points": "12889",
        "status": "OFF"
    }
]

在这种情况下,如何按状态筛选条形图?

vngu2lb8

vngu2lb81#

您应该使用“==”(双等号)比较筛选语句中的值

rects.enter().append("rect")
    .filter((d) => d.status == "ON") // This Should work now
    .attr("x", (d) => x(d.name))
    .attr("y", d => y(d.points))
    .attr("width", x.bandwidth)
    .attr("height", d => HEIGHT - y(d.points))
    .attr("fill", "steelblue")

相关问题