简体   繁体   中英

D3 Donut Chart with 0 Data

I have a D3 donut chart I've created with this code:

  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?

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.

Yes, you just need to know that dataset is not empty. Define an array of possible colors, before you pass it to .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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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