简体   繁体   English

具有 0 个数据的 D3 圆环图

[英]D3 Donut Chart with 0 Data

I have a D3 donut chart I've created with this code:我有一个用以下代码创建的 D3 甜甜圈图:

  var svg = d3.select('#chart-cont-2')
    .append('svg')
      .attr('width', width)
      .attr('height', height)

  var g = svg.append('g')
    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")

  var chart_g = g.append('g')
    .attr('class', 'chart')

  var text_g = g.append('g')
    .attr('class', 'text')

  var color = d3.scaleOrdinal()
    .domain(dataset)
    .range(['rgba(2, 168, 150, 1)', 'rgba(237, 109, 0, 1)'])

  var pie = d3.pie()
    .value((d) => d.value)

  var arc = d3.arc()
    .innerRadius(87)
    .outerRadius(77)

  chart_g.selectAll('.part')
    .data(pie(d3.entries(dataset)))
    .enter()
    .append('path')
      .attr('d', arc)
      .attr('fill', (d, i) => color(i))

There may be times when the dataset is empty.有时数据集是空的。 Is there a way I can have an rgba(2, 168, 150, 1) color donut chart when there is no data present and then switch to my coded donut chart when there is data present?有没有一种方法可以在没有数据时获得 rgba(2, 168, 150, 1) 彩色甜甜圈图,然后在有数据时切换到我的编码甜甜圈图?

EDIT : My dataset is an object:编辑:我的数据集是一个对象:

{a: 0, b: 0}

When both values are 0, I would like the donut chart in the color of rgba(2, 168, 150, 1) to show up.当两个值都为 0 时,我希望显示rgba(2, 168, 150, 1)颜色的圆环图。

Yes, you just need to know that dataset is not empty.是的,您只需要知道数据集不为空。 Define an array of possible colors, before you pass it to .range .在将其传递给.range之前,定义一组可能的颜色。

Example:例子:

var colorsRange = dataset && dataset.length ? ['rgba(2, 168, 150, 1)', 'rgba(237, 109, 0, 1)'] : ['rgba(2, 168, 150, 1)'];

var color = d3.scaleOrdinal()
   .domain(dataset)
   .range(colorsRange);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM